/************************************************************************* * * This is a stack implementation that extends the ArrayList class * *************************************************************************/ import java.util.*; public class Stack extends ArrayList implements StackInterface { public Stack() { super(); } /** * Inserts an item onto the top of the stack. */ public void push(AnyType x) { add(x); } /** * Removes and returns the item at the top of this stack. */ public AnyType pop( ) throws StackException { if(isEmpty()) throw new StackException("Stack is empty"); else return remove(size()-1); } /** * Returns the top item without its removal */ public AnyType peek() throws StackException { return get(size()-1); } /** * Returns a string representation */ public String toString() { StringBuffer str = new StringBuffer(super.toString()); str.setCharAt(0,'<'); str.setCharAt(str.length()-1,'>'); return str.toString(); } public static void main(String[] args) { Stack stk = new Stack(); stk.push(1); stk.push(5); stk.push(10); System.out.println(stk); } } /** StackInterface **/ interface StackInterface { /** * Tests if the stack is empty. */ public boolean isEmpty(); /** * Removes and returns the item at the top of this stack. */ public AnyType pop() throws StackException; /** * Returns the top item without its removal */ public AnyType peek() throws StackException; /** * Inserts an item onto the top of the stack. */ public void push(AnyType e) throws StackException; /** * Removes all items from the stack. */ public void clear(); } /** StackException **/ class StackException extends RuntimeException { public StackException(String name) { super(name); } public StackException() { super(); } }