如何将HashMap转换为自己的类型数组?

时间:2014-01-13 15:25:43

标签: java hashmap

我的哈希映射类型为:

private HashMap<String, HashMapObject> likesYearHashMap;

其中HashMapObject:

public class HashMapObject  {

private int count;
private String id;

public HashMapObject(int count, String id) {
    super();
    this.count = count;
    this.id = id;
}

}

如何将值转换为HashMap到HashMapObject []数组?

我得到了关于强制转换的错误:YearHashMap.values();

3 个答案:

答案 0 :(得分:2)

像这样:

map.values().toArray(new HashMapObject[map.size()])

答案 1 :(得分:1)

likesYearHashMap.values().toArray (new HashMapObject[likesYearHashMap.size ()])

答案 2 :(得分:0)

感谢@Vakh和@NinChimpsky,我发布了完整的解决方案:

要转换为数组:

HashMapObject[] array = new HashMapObject[likesYearHashMap.size()];
likesYearHashMap.values().toArray(array);

转换为ArrayList

Collection<HashMapObject> values = likesYearHashMap.values();
ArrayList<HashMapObject> arrayList= new ArrayList<HashMapObject>(values);