Java Reference
In-Depth Information
Ask the Expert
Q
:
Aside from arrays, what other types of collections can the for-each style
for
loop
cycle through?
A
:
One of the most important uses of the for-each style
for
is to cycle through the con-
tents of a collection defined by the Collections Framework. The Collections Frame-
work is a set of classes that implement various data structures, such as lists, vectors,
sets, and maps. A discussion of the Collections Framework is beyond the scope of
this topic, but complete coverage of the Collections Framework can be found in my
book
Java: The Complete Reference, Ninth Edition
(Oracle Press/McGraw-Hill Edu-
cation, 2014).
The for-each style
for
automates the preceding loop. Specifically, it eliminates the need
to establish a loop counter, specify a starting and ending value, and manually index the
array. Instead, it automatically cycles through the entire array, obtaining one element at a
time, in sequence, from beginning to end. For example, here is the preceding fragment re-
written using a for-each version of the
for:
With each pass through the loop,
x
is automatically given a value equal to the next element
in
nums
. Thus, on the first iteration,
x
contains 1, on the second iteration,
x
contains 2, and
so on. Not only is the syntax streamlined, it also prevents boundary errors.
Here is an entire program that demonstrates the for-each version of the
for
just de-
scribed: