Java Reference
In-Depth Information
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);
System.out.print("More items for the list? ");
19
20
answer = keyboard.nextLine();
21
if (!(answer.equalsIgnoreCase("yes")))
22
done = true ;
23
}
24
System.out.println("The list contains:");
25
for (String entry : toDoList)
26
System.out.println(entry);
27
}
28
}
29
Search WWH ::




Custom Search