如何从hashmap值中获取对象数组?

时间:2012-05-20 13:32:20

标签: java hashmap

请原谅没有详细说明问题。我相信下面的例子会告诉你我的意思。我需要从hashmap获取anObject的所有值。正如您从下面的示例中看到的那样,键将是anObject,值将是anObject的数组。

HashMap<anObject,anObject[]> testMap = new HashMap<anObject,anObject[]>(); //Define map

anObject someObject1 = new anObject("one");
anObject someObject2 = new anObject("two")

anObject[] manyObjects1 = new anObject[3];
manyObjects1[0] = new anObject(0);
manyObjects1[1] = new anObject(1);
manyObjects1[2] = new anObject(2);
anObject[] manyObjects2 = new anObject[3];
manyObjects2[0] = new anObject(0);
manyObjects2[1] = new anObject(1);
manyObjects2[2] = new anObject(2);

testMap.put(someObject1,manyObjects1);
testMap.put(someObject2,manyObjects2);

//Get anObject from all the values put into testMap
anObject[] getAllValues1 = (anObject[])testMap.values().toArray; //is this correct or
anObject[][] getAllValues2 = (anObject[][])testMap.values().toArray; //is this correct 

1 个答案:

答案 0 :(得分:0)

您想使用toArray(T[])

Collection values = testMap.values();
anObject[][] getAllValues2 = (anObject[][])values.toArray(new anObject[values.size()][]);

因为你在地图中找回了一组值,并且地图中的值是数组,所以你需要指明你正在返回一个数组数组,所以[][]