0% found this document useful (0 votes)
32 views2 pages

Using The Enhanced Foreach

The enhanced for-each loop introduced in JDK 5.0 allows automatic iteration through arrays and collections without manually incrementing a counter variable. The syntax is "for (variable : collection)" where variable represents each element accessed from the collection. This avoids more complex iteration code and works for arrays, ArrayList, HashSet, and Map entries. The for-each loop uses the Iterator interface to iterate through elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views2 pages

Using The Enhanced Foreach

The enhanced for-each loop introduced in JDK 5.0 allows automatic iteration through arrays and collections without manually incrementing a counter variable. The syntax is "for (variable : collection)" where variable represents each element accessed from the collection. This avoids more complex iteration code and works for arrays, ArrayList, HashSet, and Map entries. The for-each loop uses the Iterator interface to iterate through elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

Using the Enhanced For-Each Loop

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:

for (variable: collection)


statement

To demonstrate, the following program prints out each element passed in along the command line:

public class Args {


public static void main(String args[]) {
for (String element: args) {
System.out.println(element);
}
}
}

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:

for (int i=0; i < args.length; i++) {


System.out.println(args[i]);
}

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;

public class SysProps {


public static void main(String args[]) {
Properties props = System.getProperties();
Set<Map.Entry<Object,Object>> entrySet = props.entrySet();
for (Map.Entry entry: entrySet) {
System.out.println(entry.getKey() + " : " +
entry.getValue());
}
}
}

Notice the following line:

Set<Map.Entry<Object,Object>> entrySet = props.entrySet();

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.

for (Map.Entry entry: entrySet) {

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:

Iterator iter = ...;


while (iter.hasNext()) {
Object element = iter.next();
// process element
}

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.

You might also like