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

Why remove() Is Optional and May Throw UnsupportedOperationException

Learn that some collections provide read-only iterators that disallow remove().

Why remove() Is Optional and May Throw UnsupportedOperationException

You'll learn why some iterators don't allow you to call remove() and will throw an exception if you try.

The Core Idea

Not all collections support modification through their iterators. While the Iterator<E> interface defines a remove() method, it's marked as optional. This means some iterators are intentionally read-only and will throw an UnsupportedOperationException if you attempt to call remove().

Think of it like museums: some allow you to touch certain exhibits (modifiable collections), while others have strict "look but don't touch" policies (read-only collections). The iterator respects the rules of the collection it came from.

When Does This Happen?

You'll encounter this in several situations:

  • Unmodifiable collections: Collections created with Collections.unmodifiableList(), Collections.unmodifiableSet(), etc., provide read-only iterators.
  • Immutable collections: Collections from factory methods like List.of(), Set.of(), and Collections.singleton() don't support modification.
  • Custom implementations: Some specialized collection classes simply don't support removal for design reasons.

What It Looks Like

When you call remove() on an unsupported iterator, you get:

List<String> immutableList = List.of("A", "B", "C");
Iterator<String> iter = immutableList.iterator();

while (iter.hasNext()) {
    String element = iter.next();
    iter.remove(); // Throws UnsupportedOperationException!
}

This isn't a bug—it's intentional. The collection is telling you "I'm read-only; you can look through me but you can't change me."

Key Takeaway:
The remove() method on iterators is optional; read-only collections provide iterators that throw UnsupportedOperationException when you try to modify them, enforcing their immutability contract.