Stack源码分析

  • Stack:
    /**
 * The Stack class represents a last-in-first-out
 * (LIFO) stack of objects. It extends class Vector with five
 * operations that allow a vector to be treated as a stack. The usual
 * push and pop operations are provided, as well as a
 * method to peek at the top item on the stack, a method to test
 * for whether the stack is empty, and a method to search
 * the stack for an item and discover how far it is from the top.
 * 

* When a stack is first created, it contains no items. * *

A more complete and consistent set of LIFO stack operations is * provided by the {@link Deque} interface and its implementations, which * should be used in preference to this class. For example: *

   {@code
 *   Deque stack = new ArrayDeque();}
* * @author Jonathan Payne * @since JDK1.0 */
Java从JDK1.0提供了一种后进先出的数据结构,位于util包的Stack类,Stack类基于Vector实现,并提供了常用push、pop、peek、empty、search几个常用方法。
    public E push(E item) {
        addElement(item);

        return item;
    }
    //使用Vector的addElement方法
    //同步的出栈方法,使用Vector的removeElementAt删除栈顶元素
    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;
    }
最后,由于Vector是线程安全的,子类继承父类后,重写父类方法不带同步,需要子类自己实现自己的同步方法。

你可能感兴趣的:(java基础)