Java中的Stack是早期的遺留類,Sun/Oracle已經不推薦使用,如今只是爲了兼容遺留代碼而保留.java
以下面的代碼所示,java.util.Stack
中的實現是基於動態數組實現的,而Vector
一樣是一個被廢棄的類。數組
我的看來,這個實現有兩個問題性能
public class Stack<E> extends Vector<E> { /** * Creates an empty Stack. */ public Stack() { } public E push(E item) { addElement(item); return item; } public synchronized E pop() { E obj; int len = size(); obj = peek(); removeElementAt(len - 1); return obj; } public synchronized E peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); } public boolean empty() { return size() == 0; } public synchronized int search(Object o) { int i = lastIndexOf(o); if (i >= 0) { return size() - i; } return -1; } /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = 1224463164541339165L; }
下面是基於LinkedList
封裝的Stack
code
這裏的棧是一個裝飾器。element
import java.util.LinkedList; import java.util.NoSuchElementException; public class Stack<T> { private LinkedList<T> stack; Stack() { stack = new LinkedList<>(); } public void push(T o) { stack.add(o); } public T pop() { if (size() <= 0) { throw new NoSuchElementException("Stack is Empty."); } return stack.removeLast(); } public T peek() { if (size() <= 0) { throw new NoSuchElementException("Stack is Empty."); } return stack.getLast(); } public boolean empty() { return stack.size() == 0; } public int size() { return stack.size(); } }