Iterators
This chapter is about iterators. An iterator is an object that visits the elements of a data structure one at a time, and it is what lets Java’s enhanced for loop work on a Set.
After reading this chapter, you should be able to:
- Make a data structure work in an enhanced
forloop by implementingIterable<T>and writing its iterator, withhasNext()andnext(), for an array-backed and a node-backed structure - Distinguish
IterablefromIterator, and explain why each call toiterator()starts an independent traversal - Choose between a static nested class and an inner class based on whether the class needs its enclosing instance
- Analyze an iteration as time and auxiliary space
- Test an iterator in the shared abstract
SetTestfor element coverage, empty sets, exhaustion, and independent traversals - Explain why adding or removing an element during an iteration breaks an iterator that tracks its position with a cursor or a current node
- Make an iterator fail fast with a
modCount, so it throwsConcurrentModificationExceptionwhen the set changes during the iteration
You can download the accompanying code for this chapter: starter and solution.