Enumerators (iterators)

Bruce Eckel's Thinking in Java Contents | Prev | Next

In any collection class, you must have a way to put things in and a way to get things out. After all, that’s the primary job of a collection – to hold things. In the Vector, addElement( ) is the way that you insert objects, and elementAt( ) is one way to get things out. Vector is quite flexible – you can select anything at any time, and select multiple elements at once using different indexes.

The Java Enumeration[33] is an example of an iterator with these kinds of constraints. There’s not much you can do with one except:

  1. Ask a collection to hand you an Enumeration using a method called elements( ). This Enumeration will be ready to return the first element in the sequence on your first call to its nextElement( ) method.
  2. Get the next object in the sequence with nextElement( ).
  3. See if there are any more objects in the sequence with hasMoreElements( ).
//: CatsAndDogs2.java
// Simple collection with Enumeration
import java.util.*;
 
class Cat2 {
  private int catNumber;
  Cat2(int i) {
    catNumber = i;
  }
  void print() {
    System.out.println("Cat number " +catNumber);
  }
}
 
class Dog2 {
  private int dogNumber;
  Dog2(int i) {
    dogNumber = i;
  }
  void print() {
    System.out.println("Dog number " +dogNumber);
  }
}
 
public class CatsAndDogs2 {
  public static void main(String[] args) {
    Vector cats = new Vector();
    for(int i = 0; i < 7; i++)
      cats.addElement(new Cat2(i));
    // Not a problem to add a dog to cats:
    cats.addElement(new Dog2(7));
    Enumeration e = cats.elements();
    while(e.hasMoreElements())
      ((Cat2)e.nextElement()).print();
    // Dog is detected only at run-time
  }
} ///:~ 

You can see that the only change is in the last few lines. Instead of:

    for(int i = 0; i < cats.size(); i++)
      ((Cat)cats.elementAt(i)).print();

an Enumeration is used to step through the sequence:

while(e.hasMoreElements())
      ((Cat2)e.nextElement()).print();

With the Enumeration, you don’t need to worry about the number of elements in the collection. That’s taken care of for you by hasMoreElements( ) and nextElement( ).

//: HamsterMaze.java
// Using an Enumeration
import java.util.*;
 
class Hamster {
  private int hamsterNumber;
  Hamster(int i) {
    hamsterNumber = i;
  }
  public String toString() {
    return "This is Hamster #" + hamsterNumber;
  }
}
 
class Printer {
  static void printAll(Enumeration e) {
    while(e.hasMoreElements())
      System.out.println(
        e.nextElement().toString());
  }
}
 
public class HamsterMaze {
  public static void main(String[] args) {
    Vector v = new Vector();
    for(int i = 0; i < 3; i++)
      v.addElement(new Hamster(i));
    Printer.printAll(v.elements());
  }
} ///:~ 

Look closely at the printing method:

static void printAll(Enumeration e) {
  while(e.hasMoreElements())
    System.out.println(
      e.nextElement().toString());
}

Note that there’s no information about the type of sequence. All you have is an Enumeration, and that’s all you need to know about the sequence: that you can get the next object, and that you can know when you’re at the end. This idea of taking a collection of objects and passing through it to perform an operation on each one is powerful and will be seen throughout this book.


[33] The term iterator is common in C++ and elsewhere in OOP, so it’s difficult to know why the Java team used a strange name. The collections library in Java 1.2 fixes this as well as many other problems.



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Open source and cloud computing have long promised cost efficiencies, yet many organizations have shied away from these technologies due to security and reliability concerns. Now, open source has proven itself stable, and the cloud has become as secure—or even more secure—than on-premises implementations. Read this white paper to learn how you can get the accessibility of open source and the flexibility and affordability of cloud computing combined in a compelling storage option for companies …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds