我正在尝试修复一个代码,但我无法将它发布在这里,所以我在这里有一个精简版。
我在使用 HashMap 时得到不稳定的输出。
HashMap<Integer, String> test= new HashMap<>();
test.put(1, "one");
test.put(2, "one");
test.put(3, "one");
test.put(4,"four");
test.put(5, "one");
test.put(6, "one");
test.put(10, "one");
test.put(19, "one");
test.put(20, "Sixteen");
System.out.println(test);
HashMap<Integer, String> test3= new HashMap<>(200);
test3.put(1, "one");
test3.put(2, "one");
test3.put(3, "one");
test3.put(4,"four");
test3.put(5, "one");
test3.put(6, "one");
test3.put(10, "one");
test3.put(19, "one");
test3.put(20, "Sixteen");
System.out.println(test3);
输出
test --> {1=one, 19=one, 2=one, 3=one, 4=four, 20=Sixteen, 5=one, 6=one, 10=one}
test3--> {1=one, 2=one, 3=one, 4=four, 5=one, 6=one, 10=one, 19=one, 20=Sixteen}---> My desired output.
为什么输入值相同,结果却不同。这种排序有何不同,即元素的存储?
我无法使用第二种方法,因为尺寸是动态的,它会根据应用程序不断变化。我可以使用 TreeMap 来获得所有值的一致输出吗?
最佳答案
为什么大小不同时输出不同 –
这是因为在调用 hashmap 的 put 方法时,内部调用了 indexFor(hash,table.length)。 Table.length 不同,这意味着默认值为 16,但对于您的第二种方式,大小为 200。因此索引会有所不同。
请阅读此 article 中的更多信息
我能否将 TreeMap 用于相同的情况并获得所有值的一致输出。
在 Treemap 保证中,键将被排序,因此您将得到 {1=one, 2=one, 3=one, 4=four, 5=one, 6=one, 10=one, 19=一,20=16}
如果你想按照插入的顺序检索,你可以使用LinkedHashmap
关于java - 使用 HashMap 时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33429640/