14.3. Iterators

In the LinkedList<T> class that you developed in Chapter 13 you implemented the Iterable<> interface for getting the objects from the list. This resulted in your LinkedList<> type being able to make an iterator available. As you know, an iterator is an object that you can use once to retrieve all the objects in a collection one by one. Someone dealing cards from a deck one by one is acting as an iterator for the card deck—without the shuffle, of course. Implementing the Iterable<> interface was a much better approach to accessing the members of a list than the technique that you originally implemented, and it made the collection usable with a collection-based for loop. Using an iterator is a standard mechanism for accessing each of the elements in a collection.

It is worth noting at this point that Java also provides something called an enumerator that is defined by any class that implements the java.util.Enumeration<> generic interface type. An enumerator provides essentially the same capability as an iterator, but it is recommended in the Java documentation that you use an iterator in preference to an enumerator for collections. There's nothing particularly wrong with enumerators—it's just that the Iterator<> interface declares an optional remove() method that the Enumeration<> interface does not, and the methods in the Iterator<> interface have shorter names than those in the Enumeration<> interface, so code that uses them will be less cluttered.

Any collection ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.