We now come to the implementation of the two enumeration methods. This is how they are specified in the SearchTree class definition:
public abstract Enumeration elementsInOrder(); public abstract Enumeration elementsLevelOrder();In both cases (or for PreOrder, PostOrder etc) we have to write a method that returns an Enumeration, i.e. a member of a class implementing the interface
public interface Enumeration {
boolean hasMoreElements();
Object nextElement();
}
and we have to do this both for the EmptyTree class and for the
NodeTree class.
For the EmptyTree class, this is a formality: it is never true that an empty tree has more elements, and a call for the next element should always throw an exception. In fact this is true of any empty structure, and we define a constant empty enumeration in Figure 8.3 together with the two SearchTree enumerations for the EmptyTree subclass.
private static Enumeration theEmptyEnumeration =
new Enumeration() {
public boolean hasMoreElements() {
return false;
}
public Object nextElement() {
throw new NoSuchElementException();
}
};
public Enumeration elementsInOrder() {
return theEmptyEnumeration;
}
public Enumeration elementsLevelOrder() {
return theEmptyEnumeration;
}
|