Oracle Blog

Tips for using core Java SE APIs

Using Enhanced For-Loops with Your Classes

The author of this tip is John Zukowski, president and principal
consultant of JZ Ventures, Inc.

The enhanced for-loop is a popular feature introduced with the Java SE
platform in version 5.0. Its simple structure allows one to
simplify code by presenting for-loops that visit each element of
an array/collection without explicitly expressing how one goes from
element to element.

Because the old style of coding didn't become
invalid with the new for-loop syntax, you don't have to use an
enhanced for-loop when visiting each element of an
array/collection. However, with the new style, one's code would
typically change from something like the following:

Assuming "array" is defined to be an array of String objects,
each element is assigned to the element variable as it loops
through the array. These basics of the enhanced for-loop were covered
in an earlier Tech Tip: The Enhanced For Loop, from May 5, 2005.

If you have a class called Colony which contains a group of Penguin
objects, without doing anything extra to get the enhanced for-loop to
work, one way you would loop through each penguin element would be to
return an Iterator and iterate through the colony. Unfortunately, the
enhanced for-loop does not work with Iterator, so the following won't even compile:

It is this Iterable object which is then provided to the enhanced for
loop. By making the Colony class implement Iterable, and having
its new iterator() method return the Iterator that getPenguins()
provides, you'll be able to loop through the penguins in the
colony via an enhanced for-loop.

Keep in mind that the individual penguins are internally kept in a Set
type collection so the returned order doesn't necessarily match the
insertion order, which in this case it doesn't.

Remember to genericize the implements clause for the class "implements
Iterable<T>" and not just say "implements Iterable". With the latter,
the enhanced for-loop will only return an Object for each element.