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.
interface provides the following methods:
- boolean hasNext() - Returns true if the iteration has
- E next() - Returns the next element in the
- 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.
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
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:
- 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.