Modifying a collection structure while iterating over it.
Thrown when a method detects concurrent modification of an object when such modification is not permissible (e.g., calling `list.remove()` inside a standard for-each loop over `list`).
Java collection iterators use a fail-fast mechanism (`modCount`). If the underlying collection is modified during iteration by anything other than the Iterator's own `remove()` method, the iterator throws `ConcurrentModificationException`.
1import java.util.*;2 3public class Main {4 public static void main(String[] args) {5 List<String> items = new ArrayList<>(List.of("A", "B", "C"));6 for (String item : items) {7 if (item.equals("B")) {8 items.remove(item); // Throws ConcurrentModificationException!9 }10 }11 }12}1import java.util.*;2 3public class Main {4 public static void main(String[] args) {5 // Fix 1: Use removeIf (Java 8+)6 List<String> items = new ArrayList<>(List.of("A", "B", "C"));7 items.removeIf(item -> item.equals("B"));8 9 // Fix 2: Use Iterator's own remove method10 Iterator<String> it = items.iterator();11 while (it.hasNext()) {12 if (it.next().equals("B")) {13 it.remove(); // Safe14 }15 }16 }17}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
The for-each loop implicitly uses an `Iterator`. Calling `items.remove(item)` directly alters `items.modCount`, causing the next `iterator.next()` call to throw `ConcurrentModificationException`.