Java Reference
In-Depth Information
cause such “start to finish” operations are so common, Java defines a second form of the
for
loop that streamlines this operation.
The second form of the
for
implements a “for-each” style loop. A for-each loop cycles
through a collection of objects, such as an array, in strictly sequential fashion, from start to
finish. In recent years, for-each style loops have gained popularity among both computer
language designers and programmers. Originally, Java did not offer a for-each style loop.
However, with the release of JDK 5, the
for
loop was enhanced to provide this option. The
for-each style of
for
is also referred to as the
enhanced
for
loop
. Both terms are used in this
book.
The general form of the for-each style
for
is shown here.
for(
type itr-var : collection
)
statement-block
Here,
type
specifies the type, and
itr-var
specifies the name of an
iteration variable
that will
receive the elements from a collection, one at a time, from beginning to end. The collection
being cycled through is specified by
collection
. There are various types of collections that
can be used with the
for
, but the only type used in this topic is the array. With each iteration
of the loop, the next element in the collection is retrieved and stored in
itr-var
. The loop
repeats until all elements in the collection have been obtained. Thus, when iterating over
an array of size
N
, the enhanced
for
obtains the elements in the array in index order, from
0 to
N
-1.
Because the iteration variable receives values from the collection,
type
must be the same
as (or compatible with) the elements stored in the collection. Thus, when iterating over ar-
rays,
type
must be compatible with the element type of the array.
To understand the motivation behind a for-each style loop, consider the type of
for
loop
that it is designed to replace. The following fragment uses a traditional
for
loop to compute
the sum of the values in an array:
To compute the sum, each element in
nums
is read, in order, from start to finish. Thus, the
entire array is read in strictly sequential order. This is accomplished by manually indexing
the
nums
array by
i
, the loop control variable. Furthermore, the starting and ending value
for the loop control variable, and its increment, must be explicitly specified.