支持任何對象類型,有更多的錯誤檢查。
package Stack; /** * Created by Frank */ public class MyStack<T> implements SimpleStack<T> { public static void main(String[] args) { MyStack<String> stack = new MyStack<>(); stack.push("Frank"); stack.push("Smith"); System.out.println(stack.pop()); } private int depth = 0; public static final int DEFAULT_INITIAL = 10; private T[] stack; public MyStack() { this(DEFAULT_INITIAL); } public MyStack(int howBig) { if (howBig <= 0) { throw new IllegalArgumentException(howBig + " must be positive, but was " + howBig); } stack = (T[]) new Object[howBig]; } @Override public boolean empty() { return depth == 0; } @Override public void push(T obj) { stack[depth++] = obj; } @Override public T pop() { --depth; T tmp = stack[depth]; stack[depth] = null; return tmp; } @Override public T peek() { if (depth == 0) { return null; } return stack[depth - 1]; } }