//---------------------------------------------------------------- // ArrayStack.java by Dale/Joyce/Weems Chapter 3 // // Implements BoundedStackInterface using an array to hold the // stack elements. // // ajg version: formatting, // just one constructor it is LEGAL, but weird // (I call it the DWC--davis weird constructor) // protected->private, if-then-else //---------------------------------------------------------------- package ch03.stacks; public class ArrayStack implements BoundedStackInterface { private T[] stack; // holds stack elements private int topIndex = -1; // index of top element in stack public ArrayStack(T[] stack) { this.stack = stack; } public boolean isEmpty() { return topIndex == -1; } public boolean isFull() { return topIndex == stack.length-1; } public void push(T element) { // Throws StackOverflowException if this stack is full, // otherwise places element at the top of this stack. if (isFull()) throw new StackOverflowException("Helpful msg."); else stack[++topIndex] = element; } public void pop() { // Throws StackUnderflowException if this stack is empty, // otherwise removes top element from this stack. if (isEmpty()) throw new StackUnderflowException("Helpful msg."); else stack[topIndex--] = null; } public T top() { // Throws StackUnderflowException if this stack is empty, // otherwise returns top element from this stack. if (isEmpty()) throw new StackUnderflowException("Helpful msg."); else return stack[topIndex]; } } // Local Variables: // compile-command: "cd ../..; javac ch03/stacks/ArrayStack.java" // End: