previous | start | next

Iterable Interface

A class that implements the Iterable interface must have a method, iterator() that returns an Iterator Object for that class instance

public interface Iterable<E>
{
  public Iterator<E> iterator();

}

Java classes Stack<E>, Queue<E>, and LinkedList<E> all implement Iterable<E>

So code to print the elements in any one of these can be exactly the same:

      Stack<String> x; // or Queue<String> x;  or LinkedList<String> x;
 
      ...
      Iterator<String> p = x.iterator();

      while(p.hasNext()) {
       System.out.println(p.next());
      }
   

Another advantage for a class implementing Iterable is that the 'foreach' style loop can be used. It is implemented by the compiler as the while loop above, but can be written more simply as:

      Stack<String> x; // or Queue<String> x;  or LinkedList<String> x;
 
      ...
      for(String s: x) {
       Systme.out.println(s);
      }      
   


previous | start | next