Resources‎ > ‎Java Basics‎ > ‎

Iterators and Iterable

Iterators

A common operation is traversal of all elements of a collection.  An iterator is an object that allows you to do so in a simple way.

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. The following piece of code reads the text of a file one word at a time.

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

Notice that I have used the fully qualified names for the Scanner and File. This obviates the need to import java.util and java.io at the top of the class.

Iterable and foreach

Java also provides an Iterable interface.  Many of the data structures provided by Java are iterable, which means that they can be traversed using a foreach loop.  The foreach loop is similar to the for loop, but the syntax is more concise; the programmer need not maintain a control variable.

The following example shows two for loops, one typical for loop and the equivalent foreach loop:
ArrayList<String> al = new ArrayList<String>();
al.add("one");
al.add("two");
al.add("three");

for(int i = 0; i < al.size(); i++) {
    String s = al.get(i);
    System.out.println(s);
}

for(String s: al) {
    System.out.println(s);
}



  • String s:al - This indicates "for each string in al".  Each iteration the next string will be retrieved from the list al and stored in a variable of type String named s.  
  • The body of the loop may refer to the variable s.
  • The loop will run for each item in the list.
Comments