//<PLAINTEXT>
import java.util.*;

/**
 * AStack.java<br>
 * Illustrates the implementation of a stack based on an ArrayList.<p>
 *
 * Created: Mon Mar 24 11:26:05 2003
 *
 * @author <a href="mailto:shapiro@cse.buffalo.edu">Stuart C. Shapiro</a>
 */

public class AStack {
    private ArrayList stack;

    /**
     * Creates a new <code>AStack</code> instance.
     *
     */
    public AStack (){
	stack = new ArrayList();
    }

    /**
     * Creates a new <code>AStack</code> instance
     * with the given initial capacity.
     *
     * @param initialCapacity the initial capacity of this AStack.
     */
    public AStack (int initialCapacity){
	stack = new ArrayList(initialCapacity);
    }

    /**
     * Determines if this AStack is empty.
     *
     * @return true if this AStack has no elements in it;
     * otherwise returns false.
     */
    public boolean empty() {
	return stack.isEmpty();
    }
    
    /**
     * Adds a new Object to the top of this AStack.
     *
     * @param obj the <code>Object</code> to be pushed onto this AStack.
     */
    public void push(Object obj) {
	stack.add(obj);
    }

    /**
     * Returns the Object on the top of this AStack.
     *
     * @return the <code>Object</code> on the top of this AStack.
     * @exception NoSuchElementException if this AStack is empty.
     */
    public Object top() throws NoSuchElementException {
	try {
	    return stack.get(stack.size()-1);
	} catch (IndexOutOfBoundsException e) {
	    throw new NoSuchElementException();
	} // end of try-catch
    }

    /**
     * Removes and returns the Object on the top of this AStack.
     *
     * @return the <code>Object</code> that was on the top of this
     * AStack, after removing it.
     * @exception NoSuchElementException if this AStack is empty.
     */
    public Object pop() throws NoSuchElementException {
	Object obj = top();
	stack.remove(stack.size()-1);
	return obj;
    }

    /**
     * Returns a String representation of this AStack,
     * with the top Object shown at the left.
     *
     * @return a <code>String</code> representation of this AStack.
     */
    public String toString() {
	String result = "(";
	if (!empty()) {
	    for (int i = stack.size()-1; i > 0; i--) {
		result += stack.get(i) + ", ";
	    } // end of for (int i = stack.size()-1; i > 0; i--)
	    result += stack.get(0);
	} // end of if (!empty())
	return result + ")";
    }

}// AStack
