Why does adding an element into a HashMap work inside an IF
block while iterating it using an iterator?
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
}
Please point me to any duplicates, if any, I'll delete this question.
You are just updating the value inside the map for key 1
in the if
while outside of the if you add a new key with 5
making the size of the map bigger. Therefore you are modifying the size and the iterator fails.
In general: If you want to compare why one call works and the other not, make sure you are using exactly the same call with the same parameters. So map.put(1,4)
will work to outside the if.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.