Java Reference
In-Depth Information
▪ Annotations (metadata; see
Using and Defining Annotations
)
▪ Generic Types
▪
printf
, scanners, and the
Scanner
classes
▪ Variable arguments (varargs)
▪ Improved semantics for the Java Memory Model
▪
static import
Java 5 foreach loop
You want a convenient means of accessing all the elements of an array or collection. The
Java 5
foreach
loop syntax is as follows:
for (Type localVar : IterableOfThatType) {
...
}
For example:
for (String s : myListOfStrings) {
// use s here
}
This form of
for
is pronounced as “for each” and is referred to that way in the documenta-
tion and the compiler messages; the colon (:) is pronounced as “in” so that the statement is
read as “foreach String s in myListOfStrings.” The
String
named
s
will be given each value
from
myListOfStrings
for one pass through the loop. How is
myListOfStrings
declared?
The
foreach
construction can be used on Java arrays, on
Collection
classes, and on any-
thing that implements the
Iterable
interface. The compiler turns it into an iteration, typic-
using foreach to iterate through an array and a
List
.
Example A-1. ForeachDemo.java
String
[]
data
= {
"Toronto"
,
"Stockholm"
};
for
for
(
String s
:
data
) {