Stack.java

package edu.hawaii.ics.yucheng;

import java.util.ArrayList;
import java.util.NoSuchElementException;

/**
 * A generic stack class.
 * 
 * @param <T> The parameterized type.
 */
class Stack<T> {

    /** The array list implementing the stack. */
    private final ArrayList<T> myStack = new ArrayList<T>();


    /**
     * Clears the stack.
     */
    public void clear() {
        myStack.clear();
    }


    /**
     * Returns true if the stack is empty.
     * 
     * @return True if the stack is empty.
     */
    public boolean isEmpty() {
        return myStack.isEmpty();
    }


    /**
     * Pops a value off the stack.
     * 
     * @return The value popped off the stack.
     */
    public T pop() {
        if (myStack.isEmpty())
            throw new NoSuchElementException();
        final T item = myStack.get(myStack.size() - 1);
        myStack.remove(myStack.size() - 1);
        return item;
    }


    /**
     * Pushes a value onto the stack.
     * 
     * @param item The item.
     */
    public void push(final T item) {
        if (item == null)
            throw new NullPointerException("item");
        myStack.add(item);
    }


    /**
     * The size of the stack.
     * 
     * @return The size of the stack.
     */
    public int size() {
        return myStack.size();
    }


    /**
     * Fills an array with the values from the stack.
     * 
     * @param items The items from the stack.
     */
    public void toArray(final T[] items) {
        if (items == null)
            throw new NullPointerException("items");
        myStack.toArray(items);
    }


    /**
     * Returns the string representation of the class data.
     */
    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        for (int i = 0; i < size(); i++)
            builder.append("[" + i + "] = " + myStack.get(i) + "\n");
        return builder.toString();
    }
}
Valid HTML 4.01 Valid CSS