简体   繁体   English

如何从哈希图值获取对象数组的数组?

[英]How to get an array of object arrays from a hashmap values?

Please forgive for not elaborating the question well. 请原谅您未能很好地阐述问题。 I am sure the example below will tell you what i mean. 我确信以下示例将告诉您我的意思。 I need to get all values of anObject from a hashmap. 我需要从哈希图中获取anObject的所有值。 As u can see from the example below, the key would be anObject and the value would be an array of 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 

You'd want to use toArray(T[]) : 您想使用toArray(T[])

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

Because you're getting back an array of the values in the map, and the values in the map are arrays, you need to indicate you're getting back an array of arrays, so [][] . 因为您要返回映射中的值的数组,并且映射中的值是数组,所以需要指示您要返回一个数组的数组,因此[][]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM