Java Reference
In-Depth Information
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
EXAMPLE
for
(
Integer
element : numberList)
element = 42;
numberList
is an
ArrayList
with base type
Integer
. This for-each loop changes the
value of each element of
numberList
to
42
. (This example uses automatic boxing. So,
42
really means
new Integer(42)
.)
A good way to read the first line of the example is “For each
element
in
numberList
, do
the following.”
Display 14.2
A for-each Loop Used with an
ArrayList
(part 1 of 2)
1
import
java.util.ArrayList;
2
import
java.util.Scanner;
3
public class
ArrayListDemo
4 {
5
public static void
main(String[] args)
6 {
7 ArrayList<String> toDoList =
new
ArrayList<String>(20);
8 System.out.println(
9 "Enter list entries, when prompted.");
10
boolean
done =
false
;
11 String next =
null
;
12 String answer;
13 Scanner keyboard =
new
Scanner(System.in);
14
while
(! done)
15 {
16 System.out.println("Input an entry:");
17 next = keyboard.nextLine();
18 toDoList.add(next);
(continued)