Iterator over Lists
An iterator encapsulates the current position in the list. hasNext and next traverse node by node without revealing the internal representation.
In Java, Collection.iterator() provides an iterator. The list must not be structurally modified during iteration, otherwise a ConcurrentModificationException (fail-fast) may occur.
Advantage: Algorithms operate based on the iterator protocol, remaining decoupled from arrays versus lists.
Edge case: Calling next without a hasNext check throws NoSuchElementException.
| Method | Effect |
|---|---|
| hasNext | checks that another element remains |
| next | returns the value and advances |
| ## Where used |
for-each, streams, and collection APIs work through iterators. Fail-fast iterators in the JDK detect structural changes during iteration. Writing your own Iterator trains the pattern behind enhanced for and graph/tree traversals.
Depth
A list iterator typically retains the next node to be output. hasNext only checks if this reference exists, and next returns the value and then advances. This way, traversal does not require repeated index access.
The iterator object encapsulates a time-dependent cursor. Multiple iterators can traverse the same unmodified list independently. Structural changes during iteration, however, require clear semantics, such as fail-fast detection via a modification counter.
An optional remove operation requires additional information about the predecessor and the last returned node. Its state machine must prevent deletion before the first next or twice after the same next.
Difficulty levels
- Track cursor states of
hasNextandnext. - Compare the overall costs against index-based traversal.
- Define valid states for a removing iterator operation.
Pitfalls
hasNext must not move the cursor forward. An iterator that runs from the head to the index at each step makes a full run unnecessarily quadratic.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Beginner
- Completed: 0 users