Java Reference
In-Depth Information
There are several problems with this approach, though. It involves a lot of boilerplate code
that needs to be written every time you want to iterate over the collection. It's also hard to
write a parallel version of this
for
loop. You would need to rewrite every
for
loop individu-
ally in order to make them operate in parallel.
Finally, the code here doesn't fluently convey the intent of the programmer. The boilerplate
for
loop structure obscures meaning; to understand anything we must read though the body
of the loop. For a single
for
loop, doing this isn't too bad, but when you have a large code
base full of them it becomes a burden (especially with nested loops).
Looking under the covers a little bit, the
for
loop is actually syntactic sugar that wraps up
the iteration and hides it. It's worth taking a moment to look at what's going on under the
hood here. The first step in this process is a call to the
iterator
method, which creates a
new
Iterator
object in order to control the iteration process. We call this
external iteration
.
The iteration then proceeds by explicitly calling the
hasNext
and
next
methods on this
Iterator
.
Example 3-2
demonstrates the expanded code in full, and
Figure 3-1
shows the
pattern of method calls that happen.
Example 3-2. Counting London-based artists using an iterator
int
int
count
=
0
;
Iterator
<
Artist
>
iterator
=
allArtists
.
iterator
();
while
while
(
iterator
.
hasNext
()) {
Artist artist
=
iterator
.
next
();
iif
(
artist
.
isFrom
(
"London"
)) {
count
++;
}
}