The Iterable interface is a new interface that has been added in Java 5.0. Similar to the Iterator interface the Iterable interface exposes your data structure to the ‘for each’ command. Thus allowing you to perform not just the standard Iterator syntax on it, but the new collection style traversal. How? Read on.Looking at the Java API the only method that needs to be implemented is ‘iterator()‘. Because the ‘for each’ loop can be used on any type T, it expects to be used with generics and not the old unsafe Iterator iterator(); In this case the old way is unsafe because no type checking is performed.
 

IteratorT> iterator()Returns an iterator over a set of elements of type T.

So, as long as the class returns a generic iterator, much like it would if it was implementing the Iterator interface there is nothing extra that needs to be added. Continuing the example, here is a cut down LinkedList class from earlier using generics and the Iterable interface. Extra methods and checking has been removed for brevity.

import java.util.Iterator;
public class SingleLinkedList<E> implements Iterable<E> {
private Node head = null;
private E data = null;
public void addFirst(E toAdd) {
head = new Node(toAdd, head);
}
 
private static class Node<E> {
private Node<E>;
next = null;
private E data;
private Node(E data) {
this.data = data;
next = null;
}
 
private Node(E data, Node<E>; next) {
this.data = data;
this.next = next;
}} // Closes Node class.
 
//This method returns an iterator of type Epublic Iterator<E> 
public E data() {return data;}
 
// Simple Iterator implemenation using generics to return a generic iterator.
iterator() {return new SingleListIterator();}
 
private class SingleListIterator implements Iterator<E> {
private Node<E> at = head;
public boolean hasNext() {
return at != null;
}public E next() {
E data = at.data;
at = at.next;
return data;
}public void remove() {}
} // Closes SingleListIterator class.
} // Closes SingleLinkedList class.

That’s it. You can now perform an ‘for each’ operation on the SingleLinkedList data structure.

for (int myInt : aList) {System.out.println(myInt);}

Tech Tags: