Using an Iterator : Iterable Interface « Collections « Java Tutorial






The Iterator interface has the following methods:

  1. hasNext.
  2. next.
  3. remove.

Compared to an Enumeration, hasNext() is equivalent to hasMoreElements() and next() equates to nextElement().

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

public class MainClass {
  public static void main(String[] a) {
    Collection c = new ArrayList();
    c.add("1");
    c.add("2");
    c.add("3");
    Iterator i = c.iterator();
    while (i.hasNext()) {
      System.out.println(i.next());
    }
  }
}
1
2
3








9.36.Iterable Interface
9.36.1.Using an Iterator
9.36.2.Iterable interface: while loop and for loop
9.36.3.'for' statement for Iterable object in JDK 5 has been enhanced.
9.36.4.Creating Iterable Objects: using a for-each for loop on an Iterable object