1

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?

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Huazhe Yin
  • 355
  • 1
  • 4
  • 19
  • 3
    `"b"` become last element. I suppose that check is performed in `next` method of iterator and it is not called anymore. – talex Oct 07 '16 at 15:53
  • It is not complete duplicate. But general idea behind answers is same. – talex Oct 07 '16 at 15:56

1 Answers1

1

"b" become last element.

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

talex
  • 17,973
  • 3
  • 29
  • 66
  • I see, the hash map will check the expected mod count with the current mod count, and no matter what operations we did to the last element of hash map, the check operation will not be trigger. Since the check operation is performed before the next element, but we had reached the last element. That is why it will go through. Thanks a lot!!! – Huazhe Yin Oct 07 '16 at 16:00