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);
}
}