Enumerating a Stack
Home ] Up ] [ Enumerating a Stack ] Running the Program ]

 

 

Now, let's implement a class whose job it will be to enumerate all the values in an instance of Stack.  We'll call it StackEnumerator, and as you might expect, it implements the Enumeration interface (I chose Enumeration rather than Iterator because it's simpler):

package examples;
import java.util.Enumeration;
/**
 * Class to iterate through an instance of the above Stack class
 */
class StackEnumerator implements Enumeration
{
  /**
   * Constructor associates the StackIterator with a Stack instance
   */
  public StackEnumerator(Stack theStack)
  {
    m_theStack = theStack;
  }
  /**
   * Returns whether there are more elements
   */
  public boolean hasMoreElements()
  {
    return m_current < m_theStack.getStackSize() - 1;
  }
  /**
   * Returns the next element
   */
  public Object nextElement()
  {
    return m_theStack.get(++m_current);
  }
  private Stack m_theStack;
  private int   m_current = -1; // Position "before" first stack element
}

Note that, in order to implement this class, the Stack class needed to give it access to its internal structures -- it calls the get() method of the Stack class.  However, a get() method is not really a natural feature of a stack.  In other words, we added an artifact to the Stack's public interface (API), merely to accommodate the StackEnumerator class.  

This is not good practice!  But, as you'll see, we can use nested and inner classes to improve the situation.

 

This page was last modified on 02 October, 2007