Java Reference
In-Depth Information
Figure 4.5
An iterator, after one
iteration, pointing to
the next item to be
On the face of it, Iterator seems to offer no obvious advantages over the previous ways we
have seen to iterate over a collection, but the following two sections provide reasons why it is
important to know how to use it.
Index access versus iterators
We have seen that we have at least three different ways in which we can iterate over an
ArrayList . We can use a for-each loop (as seen in Section 4.9.1), the get method with an
integer index variable (Section 4.10.2), or an Iterator object (this section).
From what we know so far, all approaches seem about equal in quality. The first one was maybe
slightly easier to understand, but the least flexible.
The first approach, using the for-each loop, is the standard technique used if all elements of a col-
lection are to be processed (i.e., definite iteration), because it is the most concise for that case. The
two latter versions have the benefit that iteration can more easily be stopped in the middle of pro-
cessing (indefinite iteration), so they are preferable when processing only a part of the collection.
For an ArrayList , the two latter methods (using the while loops) are in fact equally good.
This is not always the case, though. Java provides many more collection classes besides the
ArrayList . We shall see several of them in the following chapters. For some collections, it is
either impossible or very inefficient to access individual elements by providing an index. Thus,
our first while loop version is a solution particular to the ArrayList collection and may not
work for other types of collections.
Search WWH ::

Custom Search