Iterator.remove keeps the iterator's internal state consistent while removing, but calling the list's own remove during a for-each still trips the fail-fast check on the next step and throws ConcurrentModificationException.
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
if (it.next() % 2 == 0) {
it.remove();
}
}
System.out.println("Evens removed safely: " + nums);
try {
for (Integer n : nums) {
if (n == 1) {
nums.remove(n);
}
}
} catch (ConcurrentModificationException e) {
System.out.println("Removing via the list during for-each throws: " + e.getClass().getSimpleName());
}
Evens removed safely: [1, 3, 5]
Removing via the list during for-each throws: ConcurrentModificationException
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-09-27