CS136, Lecture 19

  1. Enumerations and Iterators
    1. Examples of iterators
  2. Ordered Structures

Enumerations and Iterators

We often need a way of cycling through all of the elements of a data structure. There exists a built-in interface in java.util:

public interface Enumeration {
    public boolean hasMoreElements();
    // pre: Associated structure, S, is unchanged
    // post: true iff element of S has yet to be traversed.

    public Object nextElement();
    // pre: S has more unenumerated elements
    // post: returns another element of S, marks it enumerated
}

A data structure can create an object of type enumeration, which can be used to cycle through the elements. For example, built-in Java class Vector has a method:

  public Enumeration elements()

Can print out the elements of Vector v as follows:

    for (Enumeration enum=v.elements(); enum.hasMoreElement(); )
        System.out.println(enum.nextElement());

Important Notes:

  1. Never change the state of a data structure when doing an enumeration unless you know exactly how the enumeration works as may end up in an infinite loop!

  2. Order of enumeration may be quite different than you expect. Don't count on a particular order unless you know how the particular enumeration works.
Bailey has extended Enumeration interface to Iterator with more functionality:

public interface Iterator extends Enumeration {
    // hasMoreElements(), nextElement() as before

    public void reset();
    // post: the iterator is reset to beginning of traversal

    public Object value();
    // pre: traversal has more elements
    // post: returns current value referenced by the iterator 
}

Now can restart an iterator (rather than creating a new one) and also access a value without moving forward. value() returns the same object returned by the previous call of hasMoreElements().

The data structures in the structure library typically return an Iterator rather than an Enumeration.

We can now rewrite the for loop above in a slightly different manner:

    for (Iterator iter = v.elements(); iter.hasMoreElement(); iter.nextElement())
        System.out.println(iter.value());

This is now a bit clearer in showing how changes occur during each iteration of loop.

Examples of iterators

The text provides an example of the Vector Iterator. Let's look at CircularList iterator instead.

Have elements method in CircularList:

    public Iterator elements()
    // post: returns iterator to traverse list elements.
    {
        return new CircularListIterator(tail);
    }

Let's see how code actually looks:

class CircularListIterator implements Iterator
{
    protected SinglyLinkedListElement tail;
    protected SinglyLinkedListElement current;
        // element ready to look at next

    public CircularListIterator(SinglyLinkedListElement t)
    // pre: t is a reference to a circular list element
    // post: constructs iterator for traversing circular list
    {
        tail = t;
        reset();
    }

    public void reset()
    // post: resets iterator to point to head of list
    {
        if (tail == null) 
            current = null;
        else 
            current = tail.next;
    }

    public boolean hasMoreElements()
    // post: returns true if some elements not visited
    {
        return current != null;
    }

    public Object nextElement()
    // pre: hasMoreElements()
    // post: returns current element, increments iterator
    {
        Object result = current.value;
        if (current == tail) 
            current = null;
        else 
            current = current.next;
        return result;
    }

    public Object value()
    // pre: hasMoreElements()
    // post: returns current value
    {
        return current.value;
    }
}
Notes:
  1. CircularListIterator is not public. Therefore only available inside package structure. Fine, since only want it to be accessible from method elements() of CircularList. Could also define as an inner class.

  2. Some iterators take a copy of the entire data structure, while others, like CircularList, take only the parts they need (in this case the tail). For example elements method of Vector has body:
    return new VectorIterator(this);

  3. Notice constructor remembers info passes in and then calls reset. This is usual pattern for constructors of iterators.

  4. Before using Iterator, be sure to call hasMoreElements() to make sure you don't try to access something that isn't there!
Iterator are useful for printing out all elements of a data structure:
    for (Iterator iter = list.elements(); list.hasMoreElement(); 
                                                    list.nextElement())
        System.out.println(list.value());

Recall again that Iterators are great for traversing a data structure, but should not be used to change the list as the results may not be predictable!

Ordered Structures

Earlier in the term we talked about sorting arrays. The various sort routines had an interface:

import structure.Comparable;

public interface SortInterface
{
    /**  
    POST -- The elements are in non-decreasing order
    **/
    public void sort (Comparable[] elts);
}

where

public interface Comparable {
    public boolean lessThan(Comparable item);
    // pre: item is non-null
    // post: returns true iff this object less than item
}

In order to test the sorts, we created a class of elements which met that specification. Here we create a special class called an ordered association (Association was defined in chapter 1 of Bailey).

public class Association {
    protected Object theKey;   // key of the key-value pair
    protected Object theValue; // value of the key-value pair

    public Association(Object key, Object value)
    // pre: key is non-null.
    // post: constructs a key-value pair.
    {
		Assert.pre(key != null, "Key must not be null.");
		theKey = key;
		theValue = value;
    }

    public boolean equals(Object other)
    // pre: other is non-null Association
    // post: returns true iff the keys are equal
    {
		Association otherAssoc = (Association)other;
		return key().equals(otherAssoc.key());
    }
       
    public Object value()
    // post: returns value from association
    {
			return theValue;
    }

    public Object key()
    // post: returns key from association
    {
			return theKey;
    }

    public void setValue(Object value)
    // post: sets association's value to value.
    {
			theValue = value;
    }

    public String toString()
		...
}

Notice the type-cast that was needed in equals, because equals in Object takes a parameter of type Object, overridden method must take a parameter of the same type.

ComparableAssociation extends Association:

public class ComparableAssociation extends Association implements Comparable {
    public ComparableAssociation(Comparable key, Object value)
    // pre: key is non-null
    // post: constructs association of key and a value
    {
		super(key,value);
    }

     public ComparableAssociation(Comparable key)
    // pre: key is non-null
    // post: constructs association of key and null
    {
		this(key,null);
    }

    public boolean lessThan(Comparable other)
    // pre: other is non-null ComparableAssociation
    // post: returns true iff this key is less than other key
    {
       ComparableAssociation otherCA = (ComparableAssociation)other;
       Comparable thisKey = (Comparable)key();
       Comparable otherKey = (Comparable)otherCA.key();

       return thisKey.lessThan(otherKey);
    }

    public String toString()
		...
}

Note again how lessThan must perform a type cast on its parameter. Again the parameter must be of type Comparable since lessThan in Comparable does. (Isn't this annoying - a big part of my research in OO language design has been in eliminating this annoyance!).

Please read the rest of this chapter on your own. It discusses ordered vectors and ordered lists. You should understand the details of the implementations (see the code in the structures library as well as the material in the text).