ConcurrentHashMap<String, Integer> hm = new ConcurrentHashMap<>();
hm.put("1", 1);
hm.put("2", 2);
hm.put("3", 3);
Iterator<String> itr = hm.keySet().iterator();
while(itr.hasNext()){
String key = itr.next();
System.out.println(key + " : " + hm.get(key));
hm.put("4", 4);
}
System.out.println(hm);
ConcurrentHashMap<String, Integer> hm1 = new ConcurrentHashMap<>();
hm1.put("One", 1);
hm1.put("Two", 2);
hm1.put("Three", 3);
Iterator<String> itr1 = hm1.keySet().iterator();
while(itr1.hasNext()){
String key = itr1.next();
System.out.println(key + " : " + hm1.get(key));
hm1.put("Four", 4);
}
System.out.println(hm1);输出:1:1 2:2 3:3 4:4 {1=1,2=2,3=3,4=4} 1:1 2:2 3:3 {One=1,Four=4,Two=2,Three=3}
为什么会这样呢?
发布于 2017-03-31 02:20:56
interator()调用包含以下文档:https://docs.oracle.com/javase/8/docs/api/java/util/Set.html#iterator--
“返回的元素没有特定的顺序”
hm.put("4",4)
将其添加到列表的末尾(碰巧?)
hm1.put("Four",4)
将其相加到1和4之间。然而,next()运算符显然已经超过了迭代器中的这一点,因此对next()的下一次调用已经位于Two=2。
答案:
在遍历相同的列表时更改无序列表不是一个好主意。
https://stackoverflow.com/questions/43125336
复制相似问题