Junior — Middle
How can a ConcurrentModificationException be thrown during iteration over a collection?
sobes.tech AI
Answer from AI
The ConcurrentModificationException in Java occurs when the structure of a collection is modified during iteration (for example, adding or removing elements) without using the iterator.
For example, if you use an ArrayList and in a for-each loop remove an element directly from the collection, not through the iterator's remove() method, this exception will be thrown:
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
for (String s : list) {
if (s.equals("b")) {
list.remove(s); // will throw ConcurrentModificationException
}
}
This happens because the iterator tracks changes to the collection through an internal modification count (modCount). If the collection is changed directly, the counter is not synchronized with the iterator, and an exception is thrown on the next call to next() or hasNext().
To avoid this, you should use the iterator's methods to remove elements:
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if (s.equals("b")) {
iterator.remove(); // safe removal
}
}