0

请原谅没有很好地阐述这个问题。我相信下面的例子会告诉你我的意思。我需要从哈希图中获取 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 
4

1 回答 1

0

你想使用toArray(T[])

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

因为您要返回映射中的值数组,并且映射中的值是数组,所以您需要表明您要返回数组数组,所以[][].

于 2012-05-20T13:36:13.327 回答