Monday, February 07, 2011

Iterable interface and "for each" loop

Since Java SE 5.0, the new "for each" loop is supported.

To iterate a Collection, one had to go through the long way as follows:

import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;

class IterationUsingIterator
{
    public static void main(String[] args)
    {
        Collection<String> names = new ArrayList<String>();
        names.add( "Jack" );
        names.add( "Jill" );

        Iterator<String> nameIterator = names.iterator();
        while( nameIterator.hasNext() )
        {
            System.out.println( nameIterator.next() );
        }
    }
}

The same loop using "for each" syntax:

import java.util.Collection;
import java.util.ArrayList;

class IterationUsingForEach
{
    public static void main(String[] args)
    {
        Collection<String> names = new ArrayList<String>();
        names.add( "Jack" );
        names.add( "Jill" );

        for( String name : names)
        {
            System.out.println( name );
        }
    }
}


Question: When can a collection (Collection, Array etc...) participate in "for each" syntax?
Answer: When the collection implements Iterable (with a single method Iterator<T> interator()). These includes Collection, List, Set, SortedSet, Queue and a few more collection sub-interfaces (refer to the javadocs). Arrays also support "for each" syntax. But they do not have a "Is A" relationship with Iterable.

No comments: