public class Stack { private T[] stack; private int capacity; private int size; public Stack() { this(10); } public Stack(int initialCapacity) { stack = (T[]) new Object[initialCapacity]; capacity = initialCapacity; size = 0; } private void doubleCapacity() { T[] newStack = (T[]) new Object[2*capacity]; for (int i = 0; i < capacity; i++) newStack[i] = stack[i]; capacity = 2*capacity; stack = newStack; } /** Pushes item onto the stack */ public void push(T item) { if (isFull()) doubleCapacity(); stack[size++] = item; } /** Pops off an item from the stack */ public T pop() { if (isEmpty()) throw new RuntimeException("Trying to pop an empty stack."); return stack[--size]; } /** Returns the item at the top of the stack */ public T top() { if (isEmpty()) throw new RuntimeException("Trying to access an empty stack."); return stack[size-1]; } /** Returns true iff the stack is empty. */ public boolean isEmpty() { return size == 0; } /** Returns true iff the stack is full. */ private boolean isFull() { return size == capacity; } /** Returns a string representation of the stack. */ public String toString() { String s = ""; for (int i = size - 1; i >= 0; i--) s += stack[i] + " "; return s; } public static void main(String[] args) { int capacity = 10; Stack is = new Stack(capacity); if (is.isEmpty()) System.out.println("stack is empty"); else System.out.println("stack is not empty"); for (int i = 0; i < capacity; i++) is.push(i); is.push(capacity); System.out.println("stack before popping: " + is); System.out.println(is.pop()); System.out.println("stack after popping: " + is); System.out.println("top of stack is: " + is.top()); /////////////////////////////////////////////////// Stack ss = new Stack(capacity); ss.push("Now"); ss.push("is"); ss.push("the"); ss.push("time"); System.out.println(ss); } }