java - 使用 HashMap 时的奇怪行为

标签 java hashmap treemap

我正在尝试修复一个代码,但我无法将它发布在这里,所以我在这里有一个精简版。

我在使用 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/

相关文章:

java - 是否有在 Java 中编写 map 文字样式的最佳实践?

java - 改变变量会导致改变对象

java - 如何通过 Hashmap<int<arraylist>> 分配比预期更多的值来修复循环

java - 在对 Map 进行排序时确定某些字符串优先级的最佳方法

java - 需要一个 Java TreeMap<Integer, Character> 的快速替代品,它可以在不降低速度的情况下容纳许多映射

java - API 调用返回 Null

java - Java 中的线程池实际上 stop() 线程吗?

java - Rational Application Developer (RAD) 7.5+ 和 websphere 运行时不会从项目中获取 jar

javascript - IE11 中的 Array.map() 错误

java - i-1 访问 TreeMap