Pattern · Core

Iterator

Walk through a collection's elements one by one WITHOUT exposing how the collection stores them — and support multiple independent walks at once.

Asked atAmazonGoogleMicrosoft
step 1 / 8
A cursor over the collection
createsreads
«interface»
Collection
+ iterator(): Iterator
«interface»
Iterator
+ hasNext()
+ next()
BookShelf
+ iterator()
ShelfCursor
- index
+ hasNext()
+ next()
A cursor over the collection
1interface Collection { Iterator iterator(); }
2interface Iterator { boolean hasNext(); Object next(); }
3class BookShelf implements Collection {
4 Iterator iterator(){ return new ShelfCursor(this); }
5}
6class ShelfCursor implements Iterator {
7 int index = 0;
8 boolean hasNext(){ return index < shelf.size(); }
9 Object next(){ return shelf.getAt(index++); }
10}
State
Collectioniterator() factory
IteratorhasNext() / next()

Two interfaces, no storage in sight. A Collection can hand out an Iterator; an Iterator is just hasNext() and next(). Nothing here says "array" or "tree" — that's the whole point.