CSE143 Sample Program handout #29 Stack Interface --------------- public interface Stack { public void push(Object value); public Object pop(); public boolean isEmpty(); } SimpleStack Implementation -------------------------- import java.util.*; public class SimpleStack implements Stack { private ArrayList myData; public SimpleStack() { myData = new ArrayList(); } public void push(Object value) { myData.add(value); } public Object pop() { return myData.remove(myData.size() - 1); } public boolean isEmpty() { return myData.isEmpty(); } } ExtendedStack Interface ----------------------- public interface ExtendedStack extends Stack { public int length(); public Object peek(); } ComplexStack implementation of ExtendedStack -------------------------------------------- public class ComplexStack extends SimpleStack implements ExtendedStack { private int myLength = 0; public void push(Object data) { myLength++; super.push(data); } public Object pop() { myLength--; return super.pop(); } public Object peek() { Object value = super.pop(); super.push(value); return value; } public int length() { return myLength; } } Testing Program --------------- public class StackTest { public static void main(String[] args) { Stack s1 = new SimpleStack(); loadStack(s1); printStack(s1); ExtendedStack s2 = new ComplexStack(); loadStack(s2); System.out.println("length = " + s2.length()); System.out.println("peek = " + s2.peek()); printStack(s2); } public static void loadStack(Stack s) { s.push("howdy"); for (int i = 0; i < 10; i++) s.push(new Integer((int)(Math.random() * 20))); s.push("doody"); } public static void printStack(Stack s) { while (!s.isEmpty()) System.out.print(s.pop() + " "); System.out.println(); } } Output of Testing Program ------------------------- doody 14 2 12 4 8 7 18 6 16 16 howdy length = 12 peek = doody doody 17 3 6 2 17 13 9 15 14 9 howdy
Stuart Reges
Last modified: Tue May 31 21:05:48 PDT 2005