Using The Enhanced Foreach
Using The Enhanced Foreach
A new language construct for the JDK 5.0 platform is the for-each loop. This enhanced for-loop
allows you to automatically iterate through the elements of an array or collection. Instead of
manually advancing a looping variable yourself, the for-each construct manages this itself.
Instead, all you do is specify the collection to iterate through, and a variable to access each element,
as shown here:
To demonstrate, the following program prints out each element passed in along the command line:
Compile it with the JDK 5.0 compiler, and pass in some random set of command-line arguments:
javac Args.java
java Args one two three
And... you'll get the provided arguments printed out to standard output, one per line:
one
two
three
While none of this is rocket science, it avoids the more manual code block where you have to
update the index variable yourself:
The construct "for (variable: collection)" doesn't add any new keywords to the language. Instead, it
extends the meaning of the basic for loop. This for-each loop says, for each element in
"collection", assign it to the variable "element", and execute the following statement.
The construct works for both arrays and implementations of the Collection interface, like
ArrayList, HashSet, and the keys from a Map like a Properties object. To demonstrate, the
following program iterates through the System property map [available through
System.getProperties()], and displays each key-value pair:
import java.util.Map;
import java.util.Properties;
import java.util.Set;
By explicitly saying that the entrySet method of the Properties object returns a Set of
Map.Entry objects, the for-each construct doesn't require any casting operations.
That's the beauty of the Generics capabilities, also added to the J2SE 2, version 5.0 platform.
In the case of using the for-each construct with a Collection, this maps to using the Iterator
interface:
The way for-each works is it takes anything that has an iterator() method, and iterates through
the elements provided. How does it know to look for an iterator() method?
The new Iterable interface tells it so. In fact, anything that implements the Iterable interface
can be used in a for-each loop, including your own classes.