Collections Framework
Iterator
Analyze Iterator traversal cursors, safe structural mutations, and fail-fast exception states.
Interview: Focuses on Iterator remove contracts, fail-fast checks (modCount), and ConcurrentModificationException mechanics.
An Iterator is an object that enables traversing a collection, checking for next elements, and removing elements safely during traversal.
Cursor Traversal
Uses hasNext() and next() to traverse the collection sequentially.
Safe Deletion
Exposes remove(), which is the only safe way to remove elements from a collection during iteration.
Fail-Fast Checks
Detects concurrent modifications using modification counters, throwing a ConcurrentModificationException on structural changes.
The modCount validation checks
Iterators throw ConcurrentModificationException when structural changes occur during traversal:
- The collection tracks its structural mutations in a field named
modCount. - When an Iterator is created, it captures this value in
expectedModCount = modCount. - Every call to
next()orremove()verifies thatmodCount == expectedModCount. - If they do not match (e.g. because elements were added or removed directly through the collection object), it throws a
ConcurrentModificationException.
Common Pitfalls
- Calling collection.remove() in loops: Directly mutating a collection inside a loop (e.g.
list.remove(item)), which triggers aConcurrentModificationExceptionon the next iteration. - Double removal calls: Invoking the iterator's
remove()twice in a row without callingnext(), which throws anIllegalStateException.
Best Practices
- Use iterator.remove(): Always use the iterator's
remove()method when deleting elements during iteration. - Use removeIf(): Simplify iteration deletions by using
collection.removeIf(predicate).
Interview-Relevant Information
Q1: What triggers a ConcurrentModificationException?
Answer: It is thrown when a thread structurally modifies a collection (like adding or removing elements) while another iterator is traversing it. This is detected by comparing the iterator's expectedModCount with the collection's modCount.
Q2: Why does collection.remove() fail-fast inside a loop?
Answer: Calling collection.remove() increments the collection's modCount. However, the iterator's expectedModCount remains unchanged. The next call to iterator.next() detects this mismatch and throws a ConcurrentModificationException.
Quick Checklist
Can you explain modCount validation checks, write a loop that removes elements safely, and name the exception thrown during invalid modifications? If yes, you understand Iterator.
Use Cases
Safely filtering records during active collection traversals.
Processing message queues while removing handled entries.
Common Mistakes
Modifying a collection directly inside an enhanced for-loop.
Calling iterator.remove() multiple times without calling next() in between.