Java Reference
In-Depth Information
different key objects produce the same hashcode. I explain keys and hashcodes in a little more detail later in
this chapter when I discuss using maps.
Now let's look at how you can move through the objects in a collection.
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<T>
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 collec-
tion 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<T>
interface was a much better approach to
accessing the members of a list than the technique that you originally implemented, and it made the collec-
tion usable with a collection-based
for
loop. An
iterator
is a standard mechanism for accessing elements in
a collection.
NOTE
It is worth noting at this point that Java also provides something called anenumerator
that is defined by any class that implements the
java.util.Enumeration<T>
generic inter-
face type. An enumerator provides essentially the same capability as an iterator, but it is re-
commended in the Java documentation that you use an iterator in preference to an enumer-
ator for collections. There's nothing particularly wrong with enumerators — it's just that the
Iterator<T>
interface declares an optional
remove()
method that the
Enumeration<T>
in-
terfacedoesnot,andthemethodsinthe
Iterator<T>
interfacehaveshorternamesthanthose
in the
Enumeration<T>
interface, so code that uses them is less cluttered.
Any collection object that represents a set or a sequence can create an object of type
java.util.Iterator<>
that behaves as an iterator. Types representing maps do not have methods for creat-
ing iterators. However, a map class provides methods to enable the keys or objects, or indeed the key/object
pairs, to be viewed as a set, so you can then obtain an iterator to iterate over the objects in the set view of
the map.
An
Iterator<>
object encapsulates references to all the objects in the original collection in some se-
quence, and they can be accessed one by one using the
Iterator<>
interface methods that you saw in the
previous chapter. In other words, an iterator provides an easy way to get at all the objects in a collection one
at a time. Just to remind you, the basic mechanism for using an iterator in Java is illustrated in
Figure 14-4
.