2005.11.14
Supporting Java's Foreach Construct
Java 1.5 supports a new foreach construct for iterating over collections. The construct can be used on arrays and on all classes in Java's Collection framework. I searched the internet for an example on how to make my own classes iterable with this construct, but could not find an example.
Confusingly, Borland's JBuilder error documentation wrongly claimed that arguments to a foreach statement should be classes implementing the functionality of the collection class [sic]:
foreach not applicable to expression type The expression type is not a collection class or doesn't extend a collection class.
In fact, all a class needs is to implement is the Iterable interface. Here is an example I wrote, for iterating over the Fibonacci sequence.