Chapter 8. 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 further 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.
Iterators are often not used directly, because in many situations the foreach statement is more convenient: compare the code to print every element of a collection coll
using foreach:
for (Object o : coll) { System.out.println(o); ...
Get Java Generics and Collections, 2nd Edition 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.