我有一个像这样的哈希表:
HashMap<String, String[]> map = new HashMap<String, String[]>();
我希望将其转换为数组,例如Temp[],其中第一个值是来自哈希映射的键,第二个值是来自映射的String[]数组,也作为数组。这可能吗?如何实现?
请参考同样的问题链接:
hashMap.keySet().toArray(); // returns an array of keys
hashMap.values().toArray(); // returns an array of values
输出结果有问题,返回值为 [Ljava.lang.String;@1f33675 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at test.main(test.java:17)
- tetsuya嗯,你的问题很奇怪,但这是你所问的:
HashMap<String, String[]> map = new HashMap<String, String[]>();
String[] keys = map.keySet().toArray();
Object[] result = new Object[keys.length*2]; //the array that should hold all the values as requested
for(int i = 0; i < keys.length; i++) {
result[i] = keys[i]; //put the next key into the array
result[i+1] = map.get(keys[i]); //put the next String[] in the array, according to the key.
}
但是,朋友,你真的需要像这样的东西吗?无论你想做什么,超过99%的机会都不需要编写类似的代码...
我不确定这是否是您需要的,但这是我修改过的代码:
Map<String, String[]> map = new HashMap<String, String[]>();
map.put("key1", new String[]{"value1", "test1"});
map.put("key2", new String[]{"value2"});
Object[] keys = map.keySet().toArray();
Object[] values = map.values().toArray();
System.out.println("key = " + keys[0] + ", value #1 = " + ((Object[])values[0])[0]);
System.out.println("key = " + keys[1] + ", value #1 = " + ((Object[])values[1])[0] + ", value #2 = " + ((Object[])values[1])[1]);
输出:
key = key2, value #1 = value2
key = key1, value #1 = value1, value #2 = test1
key[0]
下,您有"key2"
而不是"key1"
。这是因为HashMap
不会按照添加顺序保留键。要更改这一点,您必须选择另一个Map
实现(例如,如果您想按字母顺序排列,则可以选择TreeMap
)。Object
。 toArray()
方法返回Object[]
- 一个Objects
数组,但这些对象也是数组(字符串数组 - 如您在映射中定义的)。如果您只打印value[0]
,就像打印mySampleArray
一样,其中mySampleArray
是:Object[] mySampleArray = new Object[5];
所以你调用的是整个数组而不是一个元素。这就是为什么你会得到[Ljava.lang.String;@7c6768
等(这是className@HashCode - 这是默认toString()
方法的作用)。
为了访问你的元素,你必须深入其中。
((Object[])values[0])[0]
我想你只需要编写一个方法,以实现你想要的功能。