blog dds


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.

import java.util.Iterator;
import java.math.BigInteger;

 * An Iterable interface over the Fibonacci sequence.
 * @author Diomidis Spinellis
class FibonacciSequence implements Iterable<BigInteger> {

	/** The iterator over the Fibonacci sequence. */
	private class  FibonacciIterator implements Iterator<BigInteger> {
		/** Integer n-2 of the series. */
		private BigInteger n0 = null;
		/** Integer n-1 of the series. */
		private BigInteger n1 = null;

		 * Return true.
		 * The FibonacciSequence sequence is infinite.
		public boolean hasNext() { return true; }

		/** Return the next FibonacciSequence integer. */
		public BigInteger next() {
			if (n0 == null) {
				n0 = BigInteger.ONE;
				return n0;
			} else if (n1 == null) {
				n1 = BigInteger.ONE;
				return n1;
			} else {
				BigInteger r = n0.add(n1);
				n0 = n1;
				n1 = r;
				return r;

		 * Remove an element.
		 * Nothing to see here; move on.
		public void remove() {
			throw new UnsupportedOperationException();

	/** Return an iterator for the FibonacciSequence series. */
	public Iterator<BigInteger> iterator() {
		return new FibonacciIterator();

	/** A simple test harness. */
	public static void main(String argv[]) {
		FibonacciSequence fib = new FibonacciSequence();

		for (BigInteger i : fib)

Read and post comments, or share through   

Creative Commons License Last modified: Sunday, November 13, 2005 11:27 pm
Unless otherwise expressly stated, all original material on this page created by Diomidis Spinellis is licensed under a Creative Commons Attribution-Share Alike 3.0 Greece License.