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

remove(): Removing Elements During Iteration

Use remove() to safely delete the last element returned by next() from the collection.

remove(): Removing Elements During Iteration

You'll learn how to safely delete elements from a collection while iterating over it using the Iterator's remove() method.

Why remove() Exists

Imagine you're walking through a museum gallery, looking at paintings. You have the authority to remove paintings you don't like. If you tried to yank paintings off the wall while walking forward, you'd mess up your tour route and possibly skip or revisit paintings. The remove() method is like having a curator who removes the painting you just looked at without disrupting your forward progress.

The Safe Way to Remove During Iteration

The Iterator<E> interface provides a remove() method specifically designed to delete elements while iterating. Here's the crucial detail: remove() deletes the last element that was returned by next().

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

Iterator<String> it = names.iterator();
while (it.hasNext()) {
    String name = it.next();
    if (name.equals("Bob")) {
        it.remove();  // Safely removes "Bob"
    }
}
// names now contains: ["Alice", "Charlie"]

Important Rules

  • You must call next() before calling remove() — there must be a "current element" to remove
  • You can only call remove() once per next() call
  • Calling remove() twice in a row without next() throws IllegalStateException
  • Never modify the collection directly (like list.remove(...)) during iteration — only use iterator.remove()

Why Not Direct Removal?

Using collection.remove() while iterating causes ConcurrentModificationException because the collection's structure changes unexpectedly. The iterator's remove() method safely coordinates the deletion.

Key Takeaway: Use iterator.remove() to safely delete the last element returned by next() without breaking the iteration or causing exceptions.