Search code examples
javahashmapconcurrentmodification

ConcurrentModificationException - HashMap


Consider the following code.

Map<Integer,String> map = new HashMap<Integer, String> (5);
map.put(1, "a");
map.put(2, null);
map.put(3, "b");
map.put(4, "e");
for (String str : map.values()) {
    if ("b".equals(str)) {
        map.put(5, "f");
    }
}
System.out.println(map.get(5));

It is gonna occurred ConcurrentModificationException. In this situation, I understood that we can not modify the collections which we're iterating.
However, Please Consider the following code. I only remove one line which is map.put(4,"e");
It will work!

Map<Integer,String> map = new HashMap<Integer, String> (5);
map.put(1, "a");
map.put(2, null);
map.put(3, "b");
for (String str : map.values()) {
    if ("b".equals(str)) {
        map.put(5, "f");
    }
}
System.out.println(map.get(5));


Any tips? why this is happening?


Solution

  • "b" become last element.

    The check is performed in next method of iterator and it is not called anymore.