Next: Iteration
Up: Enumerating elements
Previous: Enumerating elements
  Index
We first recall the definition of the Enumeration interface:
public interface Enumeration {
boolean hasMoreElements();
Object nextElement();
}
Our aim is to define a method
public Enumeration elements();
which returns an enumeration of the elements in the list. Then given
a linked list l, we can print out its elements, for example, by
Enumeration e = l.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
The implementation of the elements method is straightforward:
public Enumeration elements() {
return new Enumeration() {
private ListNode current = head;
public boolean hasMoreElements() {
return current != null;
}
public Object nextElement() {
if (current != null) {
Object result = current.data;
current = current.next;
return result;
} else {
throw new NoSuchElementException();
}
}
};
}
The first point to note is that this uses the Java construct of an
inner class. Such classes can be defined as members of other
classes, locally within a block of statements, or anonymously within
an expression. In this case the elements method returns a new
instance of a locally defined anonymous class. Although anonymous,
the returned class is declared to implement the Enumeration
interface by the code
return new Enumeration() { ... }
The enumeration has its own private instance variable current
which is initialised to be the head of the list. The
hasMoreElements method tests whether or not current
is null. Provided current is not null,
i.e. we have not reached the end of the list, the
nextElement method returns the current data item and moves
current to current.next. If we have reached the end
of the list, an exception is thrown. Any call to nextElement
should therefore be preceded by a check that hasMoreElements
returns true. This is done, for example, by the guard for
the while loop in the previous code:
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
Next: Iteration
Up: Enumerating elements
Previous: Enumerating elements
  Index
Peter Williams
2005-06-07