使用HashMap时的奇怪行为

Use*_*854 1 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);  
Run Code Online (Sandbox Code Playgroud)

输出

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. 
Run Code Online (Sandbox Code Playgroud)

即使输入值相同,为什么结果也不同.这种排序有何不同,即元素的存储?

我无法使用第二种方法,因为大小是动态的,它会根据应用程序不断变化.我可以使用TreeMap,并为所有值获得一致的输出.

Spr*_*ner 5

当尺寸不同时,为什么输出不同 -

这是因为在调用hashmap的put方法时,会在内部调用hashFor(hash,table.length).Table.length是不同的,这意味着默认值是16,但对于你的第二种方式,大小是200.所以索引将是不同的.

请在本文中阅读更多内容

我可以使用TreeMap,并为所有值获得一致的输出.

在树形图保证中,密钥将被订购,因此您将获得 {1=one, 2=one, 3=one, 4=four, 5=one, 6=one, 10=one, 19=one, 20=Sixteen}

如果要按插入方式检索,可以使用LinkedHashmap