The elements of a LinkedList for example, can be printed sequentially using the code
LinkedList list = new LinkedList();
... insert some elements
for (Iterator i = list.iterator(); i.hasNext();) {
System.out.println(i.next());
}
In Java 5 this for-loop can be simplified, for an
Integer
LinkedList
for example, by
LinkedList<Integer> list = new LinkedList<Integer>();
... insert some elements
for (Integer n : list) {
System.out.println(n);
}
where the colon in (Integer n : list) can be read as `in'.
For this syntax to be accepted by the compiler, the class in question must provide a method which returns an implementation of the Iterator interface, and furthermore this method must be called iterator. In Java 5 there is now an Iterable interface. A class implements this interface precisely if it provides an iterator method in the above sense. To benefit from the enhanced syntax, a class must not only provide the iterator, it must say that it does so by declaring that it implements the Iterable interface. Our own LinkedList class, for example, is defined by
public class LinkedList<E> implements Iterable<E> {
... more methods
public Iterator<E> iterator() {
return new Iterator<E>() {
... define it
};
}
}
This then permits the syntax
for (Integer n : list) {
System.out.println(n);
}
The compiler effectively replaces this code by
for (Iterator<Integer> i = list.iterator(); i.hasNext();) {
Integer n = i.next();
System.out.println(n);
}
Note, however, that this simplified syntax is only useful for certain
purposes. You will still frequently need to use the full syntax.