0

Lots of contributions here on StackOverflow provide a clear explanation as to why one should use an Iterator and its remove method to get rid of an element of a collection while iterating it (e.g. 1, 2, 3).

However, what exactly causes the ConcurrentModificationException to be thrown when one uses Collection.remove() instead of Iterator.remove()? I've been looking for a detailed answer but didn't find it. Even the The Java™ Tutorials, simply states that:

The for-each construct hides the iterator, so you cannot call remove.

What does this mean? How are the two implementations different and what is the chain of events that, in a piece of code like the one below, leads up to the exception?

Collection<String> names = new ArrayList<>();
names.add("Luke");
names.add("Leia");
names.add("Anakin");

for (String name : names) {
    if (name.equals("Anakin")) {
        names.remove(name);
    }
}
  • `java.util.AbstractList` maintains internal field called `modCount`. It's incremented every time you modify this list. ArrayList's implementation of Iterator stores value of this field, and checks it every call to `next()`, and [throws an exception](https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/util/ArrayList.java#L1040) when values don't match. – northpl93 Apr 20 '20 at 20:10
  • inside loop use names.remove(name.indexOf("Anakin")); in place of names.remove(name); and make Collection as List bcz remove method not available in Collection it present in List – Imtiyaz Ahmad Apr 20 '20 at 20:29
  • 1
    @ImtiyazAhmad why not just do `names.remove("Anakin");` *instead* of the loop… – Holger Apr 22 '20 at 13:04
  • @Holger because in question he was trying to remove inside the loop so I did inside loop – Imtiyaz Ahmad Apr 23 '20 at 15:03

0 Answers0