Java经典实例:进阶版堆栈实现,支持任何对象类型
支持任何对象类型,有更多的错误检查。
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]; } }