Skip to main content
Collections framework · Topic 7 of 8

Iterator and fail-fast

Definition​

An Iterator walks a collection one item at a time and is the safe way to remove items while looping. Most collections are fail-fast: if you change them during a for-each loop, they throw ConcurrentModificationException.

Example code​

The wrong way to remove while looping, and two right ways

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class Demo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));

try {
for (Integer n : numbers) {
if (n % 2 == 0) numbers.remove(n); // wrong: changes the list while looping
}
} catch (java.util.ConcurrentModificationException e) {
System.out.println("fail-fast: ConcurrentModificationException");
}

Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
if (iterator.next() % 2 == 0) iterator.remove(); // right: the iterator removes safely
}
System.out.println(numbers);

numbers.removeIf(n -> n > 3); // also right, and shortest
System.out.println(numbers);
}
}

// Output:
// fail-fast: ConcurrentModificationException
// [1, 3, 5]
// [1, 3]

Finished this page? Track your progress (saved only in your browser).