HashMap存储是无序的,但是null作为key一直存储在第一个位置

@Test
public void test(){
HashMap<String, String> testMap = new HashMap<String, String>();
testMap.put("apple", "苹果");
testMap.put("banana", "香蕉");
testMap.put(null, null);
testMap.put("orange", "橘子");
testMap.put("watermelon", "西瓜");
System.out.println();

Iterator it = testMap.keySet().iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}

看到一篇文章讨论到HashMap存储时null作为key的entry会存储在第一个位置,所以我写了如上代码测试。

经过测试,null作为key永远被第一个输出。当然也许这里会受到获取方法的影响,所以打断点调试是必要的。

调试的过程中,观察testMap变量的值,null这个key会被放到第一位。

HashMap存储是无序的,但是null作为key一直存储在第一个位置。但是这种讨论其实是没有什么意义的,因为获取HashMap的内容一般都是根据key获取value。不会去考虑它的顺序。

posted @ 2016-12-12 12:56  童话2017  阅读(1807)  评论(0编辑  收藏  举报