ArrayStack.java

Download
1/*2 * ArrayStack.java3 *4 * Computer Science S-22, Harvard University5 */6 7/*8 * A generic class that implements our Stack interface using an array.9 */10public class ArrayStack<T> implements Stack<T> {11    private T[] items;     // the items on the stack12    private int top;       // the index of the top item13    14    /*15     * Constructs an ArrayStack object with the specified maximum size16     * for a stack that is initially empty.17     */18    public ArrayStack(int maxSize) {19        if (maxSize <= 0) {20            throw new IllegalArgumentException("max size must be positive");21        }22        items = (T[])new Object[maxSize];23        top = -1;24    }25    26    /* 27     * isEmpty - returns true if the stack is empty, and false otherwise28     */29    public boolean isEmpty() {30        return (top == -1);31    }32    33    /*34     * isFull - returns true if the stack is full, and false otherwise 35     */36    public boolean isFull() {37        return (top == items.length - 1);38    }39    40    /* 41     * push - adds the specified item to the top of the stack.42     * Returns false if the stack is full, and true otherwise.43     */44    public boolean push(T item) {45        if (item == null) {46            throw new IllegalArgumentException();47        } else if (isFull()) {48            return false;49        }50        top++;51        items[top] = item;52        return true;53    }54    55    /* 56     * pop - removes the item at the top of the stack and returns a57     * reference to the removed object.  Returns null if the stack is58     * empty.59     */60    public T pop() {61        if (isEmpty()) {62            return null;63        }64        T removed = items[top];65        items[top] = null;66        top--;67        return removed;68    }69    70    /* 71     * peek - returns a reference to the item at the top of the stack72     * without removing it. Returns null is the stack is empty.73     */74    public T peek() {75        if (isEmpty()) {76            return null;77        }78        return items[top];79    }80    81    /*82     * toString - converts the stack into a String of the form 83     * {top, one-below-top, two-below-top, ...}84     */85    public String toString() {86        String str = "{";87        88        for (int i = top; i >= 0; i--) {89            str = str + items[i];90            if (i > 0) {91                str = str + ", ";92            }93        }94        95        str = str + "}";96        return str;97    }98}