Junior — Middle
Why does a ConcurrentModificationException occur when modifying an ArrayList simultaneously during iteration?
sobes.tech AI
Answer from AI
The ConcurrentModificationException occurs when the structure of an ArrayList is modified during iteration (for example, adding or removing elements) not through the iterator. The ArrayList iterator contains an internal modification count (modCount), which increases with changes to the list. When calling iterator methods (like next()), it checks whether the current modCount matches the one saved when the iterator was created. If they do not match, it means the collection was modified outside the iterator, and a ConcurrentModificationException is thrown to warn about potentially incorrect operations on the collection.
Example:
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
for (String s : list) {
if (s.equals("b")) {
list.remove(s); // will cause ConcurrentModificationException
}
}
The correct way to remove elements during iteration is to use the iterator's own methods:
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.equals("b")) {
it.remove(); // safe
}
}