Java Reference
In-Depth Information
Chapter 28. Iterator
In ordinary development, you add behavior by extending classes with new methods.
Occasionally, though, you need to add behavior to a collection of instances of the classes you
create. The Java class libraries provide many features for working with collections, including
behaviors for sorting, shuffling, reversing, and iterating over a collection. You may find,
however, that you need iteration behaviors that go beyond those built into Java. In particular,
if you need to add type safety to iteration, or if you need to create a new type of collection,
you will probably need to develop your own iterator code to walk through the collection. The
intent of the I TERATOR pattern is to provide a way to access the elements of collection
sequentially.
Type-Safe Collections
When you pass a collection of objects to a client, you will often imply that the contents of the
collection are instances of a certain type. For example, if you have a static method
getPromotionalFireworks() that returns an instance of List , the implication is that
the list contains instances of the Firework class. You can strengthen this type of contract by
creating a FireworkList class that guarantees that its contents are instances of Firework .
Figure 28.1 shows this class.
Search WWH ::




Custom Search