Home  >  Article  >  Java  >  Graphical code analysis of Java collection Stack

Graphical code analysis of Java collection Stack

黄舟
黄舟Original
2017-03-13 17:41:361709browse

Stack is a stack, and its feature is FILO (First In Last Out). Stack inherits from Vector (vector queue). Since Vector is implemented with the same array, Stack also uses an array instead of a linked list.

The relationship between Stack and Collection is as follows:



##Source code based on Java8:

public  class Stack<E> extends Vector<E> {

    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;
    }

    //序列版本号
    private static final long serialVersionUID = 1224463164541339165L;
}

The above is the detailed content of Graphical code analysis of Java collection Stack. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn