2012-05-20 176 views
0

请原谅没有详细说明问题。我确信下面的例子会告诉你我的意思。我需要从hashmap中获取anObject的所有值。正如你可以从下面的例子看到的,关键是anObject,并且该值将是一个anObject数组。如何从hashmap值获取对象数组的数组?

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

这些都不会编译。 – Jeffrey

+1

优先于数组的集合(列表,集合等)。不需要将它们转换为数组:它们可以直接迭代,并且有很多数组没有的有用方法和功能。 –

+0

是的,我需要帮助大声笑。这就是为什么我发布 – user859385

回答

0

你想使用toArray(T[])

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

因为你找回在地图中值的数组,并在地图中的值是数组,你需要指出你回来的是一组数组,所以[][]

+0

哦谢谢你!你救了我的一天! – user859385

+0

@ user859385:不用担心。注意编辑,结果你需要从'toArray'返回。 –

+0

原来它没有工作:(。似乎我有一个支架或某种失踪 Station [] [] allValues = values.toArray(Station [] [values.size()]); – user859385