Collections - Iterable collections and Iterators

Table of Contents

Iterable collections

For many applications, the client’s requirement is just to process each of the items in some way, or to iterate through the items in the collection. This paradigm is so important that it has achieved first-class status in Java and many other modern languages (the programming language itself has specific mechanisms to support it, not just the libraries). With it, we can write clear and compact code that is free from dependence on the details of a collection’s implementation. For example, suppose that a client maintains a collection of transactions in a Queue, as follows:

Queue<Transaction> collection = new Queue<Transaction>();

If the collection is iterable, the client can print a transaction list with a single statement:

for (Transaction t : collection) {
        StdOut.println(t);
}

This client code does not need to know anything about the representation or the implementation of the collection; it just wants to process each of the items in the collection. The same for loop would work with a Bag of transactions or any other iterable collection. We could hardly imagine client code that is more clear and compact. Supporting this capability requires extra effort in the implementation, but this effort is well worthwhile.

Tags

  1. Iterator pattern
  2. Collections - Iterators and Enumeration

Links to this note