Course contentsShow
← Java
Lesson 1303 of 2,87029. Iterators and IterableFree lesson

Safe Removal with Iterator.remove()

Learn why iterator.remove() is safe during iteration while collection.remove() causes fail-fast exceptions.

Safe Removal with Iterator.remove()

You'll learn why iterator.remove() is the safe way to remove elements during iteration, while calling collection.remove() triggers fail-fast exceptions.

The Problem with Direct Collection Removal

When you iterate over a collection and try to remove elements using the collection's own remove() method, you're modifying the collection's structure behind the iterator's back. This changes the internal modCount counter, which the iterator checks on each operation. The mismatch triggers a ConcurrentModificationException immediately.

List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
for (String name : names) {
    if (name.equals("Bob")) {
        names.remove(name); // THROWS ConcurrentModificationException!
    }
}

The Iterator.remove() Solution

The Iterator interface provides its own remove() method specifically designed for this scenario. When you call iterator.remove(), it:

  • Removes the last element returned by next()
  • Updates the collection's structure safely
  • Adjusts its own internal state to stay synchronized
  • Updates modCount but also updates the iterator's expected count
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
Iterator<String> it = names.iterator();
while (it.hasNext()) {
    String name = it.next();
    if (name.equals("Bob")) {
        it.remove(); // Safe! No exception.
    }
}
// names now contains ["Alice", "Charlie"]

Think of It This Way

Imagine a librarian (the iterator) walking through shelves. If someone else removes books directly from the shelves, the librarian loses track of their position. But if the librarian removes books themselves, they can adjust their position accordingly.

Key Takeaway: Always use iterator.remove() instead of collection.remove() when removing elements during iteration. The iterator knows how to maintain its consistency while modifying the underlying collection.