Java經典實例:進階版堆棧完成,支持任何對象類型。本站提示廣大學習愛好者:(Java經典實例:進階版堆棧完成,支持任何對象類型)文章只能為提供參考,不一定能成為您想要的結果。以下是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]; } }