O'Reilly logo

Java Generics and Collections by Philip Wadler, Maurice Naftalin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required