I have below codes and i would expect from case 2 scenario to throw ConcurrentModificationException
,but it runs successfully. As I know If i do the same thing with single key in map it does not throw exception because here
but again when I am reproducing this scenario having multiple keys with two cases -
- modification by new key.
- modification by existing key.
Case 1:
Map<String,String> mp = new HashMap<String,String>();
mp.put("1", "10");
mp.put("2", "11");
mp.put("3", "12");
mp.put("4", "13");
for (String key :mp.keySet()) {
mp.put("5", "14");
}
This will work as expected , throws ConcurrentModificationException
.
Case 2:
Map<String,String> mp = new HashMap<String,String>();
mp.put("1", "10");
mp.put("2", "11");
mp.put("3", "12");
mp.put("4", "13");
for (String key :mp.keySet()) {
mp.put(key, "14");
}
It will not throws ConcurrentModificationException
. Why ??