Java Reference
In-Depth Information
The “for-each” Loop
In Chapter 16, we will cover a family of classes known as
collections
. The
ArrayList
classes are our first examples of collection classes. Starting with version 5.0, Java
has added a new kind of
for
loop that can cycle through all the elements in a
collection and can, in particular, cycle through all the elements in an
ArrayList
.
This new kind of
for
loop is called a
for-each loop
or
enhanced for loop
. A for-
each loop can also be used to cycle through all the elements in an array. The for-
each loop was introduced for use with arrays in a starred section of Chapter 6, but
you need not go back and read that subsection. The presentation of for-each loops
here is complete.
For example, the following code ends with a for-each loop that outputs all the ele-
ments in the
ArrayList
named
mylist
:
for-each loop
ArrayList<String> myList =
new
ArrayList<String>(20);
<
Some code to fill
myList
>
for
(String element : myList)
System.out.println(element);
You can read the line beginning with
for
as “for each
element
in
myList
do the follow-
ing.” Note that the variable,
element
, has the same type as the elements in the
Array-
List
. The variable, in this case
element
, must be declared in the for-each loop as we
have done. If you attempt to declare
element
before the for-each loop, you will get a
compiler error message.
The general syntax for a for-each loop statement is
for
(
Base_Type
Variable
:
Collection_Object
)
Statement
Be sure to notice that you use a colon (not a semicolon) after the
Variable
. You may use
any legal variable name for the
Variable
; you do not have to use
element
. The only
Collection_Object
s we have seen so far are arrays and
ArrayList
objects. Although it is
not required, the
Statement
typically contains the
Variable
. When the for-each loop is
executed, the
Statement
is executed once for each element of the
Collection_Object
.
More specifically, for each
element
of the
Collection_Object
, the
Variable
is set to the
collection element and then the
Statement
is executed.
The program in Display 14.2 includes an example of a for-each loop as well as
examples of some of the other
ArrayList
details we have presented.
For-each Loop for
ArrayList
Objects
SYNTAX
for
(
Array_Base_Type
Variable
:
ArrayList_Object
)
Statement
(continued)