Iterator Interface in Java

In Java, an Iterator is a construct that is used to traverse or step through the collection.
In order to use an Iterator, you need to get the iterator object using the iterator() method of the collection interface. Java Iterator is a collection framework interface and is a part of the java.util package. Using Java Iterator we can iterate through the collection of objects.
Java Iterator interface replaces the enumerator that was used earlier to step through some simple collections like vectors.The java.util.Iterator<E> interface provides for one-way traversal and java.util.ListIterator<E> provides two-way traversal.  Iterator<E> is a replacement for the older Enumeration class which was used before collections were added to Java.
The java.util.Iterator interface provides the following methods: 
  • boolean hasNext() – Returns true if the iteration has more elements.
  • E next() – Returns the next element in the iteration.
  • void remove() – Removes from the underlying collection the last element returned by the iterator (optional operation).

The java.util.Scanner class is an example of a class that implements the Iterator interface. 

java.util.Scanner s = new java.util.Scanner(new java.io.File("test.txt"));
while(s.hasNext()) { 
 System.out.println(s.next());
}

The major differences between Java Iterator and Enumerator are:

  • Considerable improvement in method names.
  • You can remove method elements from the collection that is being traversed using an iterator.
In the example below is the  example of Iterator interface .

import java.util.*;
public class ArrayListIteratorTest {
 public static void main(String[] args) {
  ArrayList al1 = new ArrayList();
  al1.add("one");al1.add("two");
  al1.add("three");
  Iterator i = al1.iterator();
  String l;
  while(i.hasNext()) {
   l = (String)i.next();
   System.out.println(l);
  }
 }
}

Output:

one

two
three