Example 1
Home ] Up ] [ Example 1 ] Running Example 1 ] An Improvement ] Example 2 ] Running Example 2 ]

 

 

Now, I've pulled the StackEnumerator class into the Stack class as a static nested class.

I made no changes to the contents of the StackEnumerator class in the process, although I changed its name to simply Enumerator -- since it's inside the Stack class, it should be clear that it's a stack Enumerator.

Here's what the new Stack class looks like:

package staticNesting;
import java.util.Enumeration;
/**
 * Stack implements a simple stack of integers
 */
public class Stack
{
  /**
   * Creates a stack of specified number of elements
   */
  public Stack(int size)
  {
    m_stackData = new int[size];
  }
  /**
   * Pushes an integer value on the stack,
   * or throws an exception, if insufficient space
   */
  public void push(int value) throws IllegalStateException
  {
    if (m_next >= m_stackData.length)
      throw new IllegalStateException("Stack full");
    m_stackData[m_next++] = value;
  }
  /**
   * Returns whether the stack is currently empty
   */
  public boolean isEmpty()
  {
    return (m_next == 0);
  }
  /**
   * Pops the top int value off the stack,
   * or throws an exception if the stack is empty
   */
  public int pop() throws IllegalStateException
  {
    if (isEmpty())
      throw new IllegalStateException("Stack empty");
    return m_stackData[--m_next]; // top item on stack
  }
  /**
   * Returns the current size of the stack
   */
  public int getStackSize()
  {
    return m_next;
  }
  /**
   * Returns the maximum size of the stack
   */
  public int getMaxStackSize()
  {
    return m_stackData.length;
  }
  /**
   * Return the value of the specified item in the stack
   * or throws an exception if the index specified is invalid.
   */
  public int get(int index) throws IllegalArgumentException
  {
    if (index < 0 || index >= getStackSize())
      throw new IllegalArgumentException("index = " + index);
    return m_stackData[index];
  }
  private int[] m_stackData;
  private int   m_next = 0; // Index of last item in stack
  /**
   * A static nested class to iterate through an instance of this Stack
   */
  public static class Enumerator implements Enumeration
  {
    /**
     * Constructor associates the StackIterator with a Stack instance
     */
    public Enumerator(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
  }
}
 

This page was last modified on 02 October, 2007