Chapter 11. Preliminaries

In this chapter, we will take time to discuss the concepts underlying the framework, before we get into the detail of the collections themselves.

Iterable and Iterators

An iterator is an object that implements the interface Iterator:

public Iterator<E> {
  boolean hasNext();   // return true if the iteration has more elements
  E next();            // return the next element in the iteration
  void remove();       // remove the last element returned by the iterator
}

The purpose of iterators is to provide a uniform way of accessing collection elements sequentially, so whatever kind of collection you are dealing with, and however it is implemented, you always know how to process its elements in turn. This used to require some rather clumsy code; for example, in earlier versions of Java, you would write the following to print the string representation of a collection’s contents:

// coll refers to an object which implements Collection
// ----- not the preferred idiom from Java 5 on -------
for (Iterator itr = coll.iterator() ; itr.hasNext() ; ) {
  System.out.println(itr.next());
}

The strange-looking for statement was the preferred idiom before Java 5 because, by restricting the scope of itr to the body of the loop, it eliminated accidental uses of it elsewhere. This code worked because any class implementing Collection has an iterator method which returns an iterator appropriate to objects of that class. It is no longer the approved idiom because Java 5 introduced something better: the ...

Get Java Generics and Collections now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.