Java 为什么在迭代HashMap时在IF块中添加元素会起作用?

Java 为什么在迭代HashMap时在IF块中添加元素会起作用?,java,Java,为什么在使用迭代器迭代时,将元素添加到HashMap中在IF块中起作用 HashMap<Integer, Integer> map = new HashMap<>(); map.put(1, 1); map.put(2, 2); map.put(3,3); Iterator<Integer> it = map.keySet().iterator(); while(it.hasNe

为什么在使用迭代器迭代时,将元素添加到HashMap中在
IF
块中起作用

    HashMap<Integer, Integer> map = new HashMap<>();  
    map.put(1, 1);  
    map.put(2, 2);  
    map.put(3,3);  
      
    Iterator<Integer> it = map.keySet().iterator();  
    while(it.hasNext()) {  
        Integer key = it.next();  
        System.out.println("Map Value:" + map.get(key));  
        if (key.equals(2)) {  
            map.put(1, 4);                                 // Works, Why?
        }  
        //map.put(5, 5);                                   // ConcurrentModificationException, as expected
    } 
HashMap map=newhashmap();
图.put(1,1);
地图.put(2,2);
图.put(3,3);
迭代器it=map.keySet().Iterator();
而(it.hasNext()){
Integer key=it.next();
System.out.println(“映射值:“+Map.get(key));
如果(键等于(2)){
map.put(1,4);//有效,为什么?
}  
//map.put(5,5);//ConcurrentModificationException,如预期的那样
} 

请给我指出任何重复项,如果有,我将删除此问题。

您只是在地图内部更新
if
中键
1
的值,而在地图外部添加一个带有
5
的新键,使地图更大。因此,您正在修改大小,迭代器将失败


一般来说:如果要比较一个调用工作和另一个不工作的原因,请确保使用的是具有相同参数的完全相同的调用。所以
map.put(1,4)
将在if之外工作。

噢,我真傻P