從源碼理解Stack.java

package java.util;

/**
 * Stack類表示了後進先出(LIFO)的一個容器對象。Stack繼承自Vector並擴展了五個操作,使得Vector可以被看作是一個Stack。
 * 常用的push和pop,以及獲取棧頂元素的peek,測試棧是否爲空的empty,一個搜索操作search並返回其與棧頂的距離
 * 第一次創建的時候,棧中沒有元素
 * 更豐富更兼容的LIFO操作由Deque接口提供,Deque使用起來比Stack更好,比如:
 *  Deque<Integer> stack = new ArrayDeque<Integer>();
 */
public class Stack<E> extends Vector<E> {
    /**
     * 構造一個空的Stack
     */
    public Stack() {
    }

    /**
     * 向棧頂壓入元素,和addElement(item)等效
     * @param   item   the item to be pushed onto this stack.
     * @return  the <code>item</code> argument.
     * @see     java.util.Vector#addElement
     */
    public E push(E item) {
    		//調用Vector的addElement
        addElement(item);

        return item;
    }

    /**
     * 移除並返回棧頂元素
     * @return  The object at the top of this stack (the last item
     *          of the <tt>Vector</tt> object).
     * @throws  EmptyStackException  if this stack is empty.
     */
    public synchronized E pop() {
        E       obj;
        int     len = size();
        	//獲取棧頂元素
        obj = peek();
        	//移除元素
        removeElementAt(len - 1);

        return obj;
    }

    /**
     * 不移除,只返回棧頂元素
     * @return  the object at the top of this stack (the last item
     *          of the <tt>Vector</tt> object).
     * @throws  EmptyStackException  if this stack is empty.
     */
    public synchronized E peek() {
        int     len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }

    /**
     * 測試是否爲空
     * @return  <code>true</code> if and only if this stack contains
     *          no items; <code>false</code> otherwise.
     */
    public boolean empty() {
        return size() == 0;
    }

    /**
     * 返回指定元素與棧頂元素的最近距離,對象比較使用equals方法,棧頂元素爲座標起點1
     * @param   o   the desired object.
     * @return  the 1-based position from the top of the stack where
     *          the object is located; the return value <code>-1</code>
     *          indicates that the object is not on the stack.
     */
    public synchronized int search(Object o) {
    		//獲取指定元素的下標
        int i = lastIndexOf(o);
        	//size-i爲棧頂與當前元素的距離
        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = 1224463164541339165L;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章