Java Reference
In-Depth Information
This is the new syntax that tells the compiler that we are putting
String
s into
the
List
. The compiler will enforce that and give a compile time error if we
try to add any other type to the
List
.
Now we come to the
for
loop. Read it as “for
str
in
loa
” or “for
String
values of
str
iterating over
loa
.” We will get an iterator working out of sight
that will iterate over the values of
loa
, our
List
. The values (the result of the
next()
method) will be put in the
String
variable
str
. So we can use
str
inside the body of the loop, with it taking on successive values from the
collection.
Let's describe the syntax, then, as
for ( SomeType variable : SomeCollectionVariable ) {
}
which will define
variable
to be of type
SomeType
and then iterate over the
SomeCollectionVariable
. Each iteration will execute the body of the loop,
with the variable set to the
next()
value from the iterator. If the collection is
empty, the body of the loop will not be executed.
This variation of the
for
loop works for arrays as well as for these new
typed collections. The syntax for arrays is the same. Example 3.16 will echo the
arguments on the command line, but without loading up a
List
like we did
in our previous example.
Example 3.16
A
for
loop iterator for arrays
import java.util.*;
public class
Forn
{
public static void
main(String [] args)
{
for(String str : args) {
System.out.println("arg="+str);
}
} // main
} // Forn