// file: OpenListEnumeration.java // author: Robert M. Keller // purpose: Illustrate implementation of an Enumeration, one for OpenLists import java.util.*; /** * An OpenListEnumeration is a class implementing the java.util.Enumeration * interface. This allows the creation of Enumeration objects for OpenLists. */ class OpenListEnumeration implements java.util.Enumeration { /** * Error message for NoSuchElementException */ String noSuchElement = "No such element in OpenListEnumeration"; /** * the remainder of the OpenList being enumerated */ private OpenList remainder; /** * Create an OpenListEnumeration for the OpenList. * @param theList the OpenList to be enumerated */ public OpenListEnumeration(OpenList theList) { remainder = theList; } /** * Indicate whether there are elements remaining in the enumeration. * @return true if there are elements remaining, false otherwise */ public boolean hasMoreElements() { return remainder.nonEmpty(); } /** * Get the next element in the enumeration */ public Object nextElement() throws NoSuchElementException { if( remainder.isEmpty() ) { throw new NoSuchElementException(noSuchElement); } Object result = remainder.first(); remainder = remainder.rest(); return result; } /** * Test OpenListEnmeration */ public static void main(String arg[]) { OpenList L = OpenList.list("a", "b", "c", "d"); Enumeration it = new OpenListEnumeration(L); while( it.hasMoreElements() ) { System.out.println(it.nextElement()); } it = new OpenListEnumeration(L); OpenList M = OpenList.solidify(it); System.out.println(M); System.out.println(it.nextElement()); // Intentionally cause exception } }