Algorithms and Data Structures
Quick Links
What's New 
Home 
Contacts 
Course Book 
Java Book 
JDK & JDSL 
Slides 
Notes 
Demos 
Exercises 
Marks
 
Enumeration 
 
See TIJ272, and DSA137 and 142 

An Enumeration allows us to iterate over all items in a collection. For example, we might have a program loop where we want to process all items in a one dimensional array, or all elements of a list, stack, or queue. An example of enumeration of a list might be to sum up all items in the list. 

Below is an enumerator for the List class defined earlier: 

import java.util.*;

class ListEnumerator implements Enumeration{
  private List L;

  public ListEnumerator(List x){L=x;}

  public boolean hasMoreElements(){return !L.isEmpty();}

  public Object nextElement(){
    Object x = L.head();
    L = L.tail();
    return x;
  }
}
It is quite simple, but first we must note that the return type of the nextElement method of an Enumeration is an object. So, our ListEnumerator above only works for a List of objects. 

When we create a ListEnumerator object 

   Enumerator e = new ListEnumerator(X) // where X is a List
the ListEnumerator object e has a member variable L that points to (or you might prefer to think "has a handle to") the list X. We can then traverse that List L with the nextElement method. This simply gets a local variable x (an Object) to take the value of the head of the List L, lets L become the tail of L, and then return the Object x as a result. 

We also require the method hasMoreElements. This just tests if the list is empty, and delivers true if the List L is NOT empty. 

So, assume we have a list X of objects. We could print all the elements in the list as follows. 

  Enumerator e = new ListEnumerator(X);
  while (e.hasMoreElements())
   System.out.println(e.nextElement());
But what about our IntList? That's a bit of a problem, because we want our IntList methods to deliver integers, not objects. So, our IntListEnumerator cannot extend Enumerator. This is again similar to the problem we had earlier with inheritance. However, it does not stop us from using the Enumeration class as a pattern. We can then define overload, rather than override, the hasMoreElements and nextElement methods. Our IntListEnumerator class now looks as follows: 
import java.util.*;

class IntListEnumerator{
  private IntList L;

  public IntListEnumerator(IntList x){L=x;}

  public boolean hasMoreElements(){return !L.isEmpty();}

  public int nextElement(){
    int x = L.head();
    L = L.tail();
    return x;
  }
}
It's almost identical to what we have above, except that we have different return types. To see how this all hangs together have a look at the code in List6 

Note that we also have Enumeration implemented for the ArrayStack. Have a look at it here. This also shows us how we link into the jdsl. 


Copyright © Patrick Prosser 1999.