The iterator detects structural changes and fails fast. This is a feature - it stops you reading a corrupted sequence.
var list = new ArrayList<>(List.of("a", "b", "c"));
try {
for (String s : list) {
if (s.equals("b")) list.remove(s);
}
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException as expected");
}
var it = list.iterator();
while (it.hasNext()) {
if (it.next().equals("b")) it.remove();
}
System.out.println("Iterator.remove is the safe way: " + list);
Iterator.remove is the safe way: [a, c]
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30