JDK source code analysis---Stack

1 Overview

Stack is the implementation class of the stack, and the characteristic of the stack is first in, last out. Inherit Vector, rewrite 5 methods, and extend Vector.

2. Class diagram

Insert picture description here

Inherited Vector

3. Main method

3.1push

Call the addElement method of the parent class and add it to the end of the array, which is the top of the stack

public E push(E item) {
    
    
    addElement(item);

    return item;
}

3.2 pop

Play operation.

public synchronized E pop() {
    
    
    E obj;
    int len = size();
    obj = peek();//出栈
    removeElementAt(len - 1);//删除数组中的最后一个元素

    return obj;//返回栈顶
}

3.3 peek

Call the elementAt method of the parent class, and the incoming parameter is size()-1, which is the last element of the array, which is the top of the stack.

public synchronized E peek() {
    
    
    int len = size();

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

3.4 empty

Determine whether it is empty

public boolean empty() {
    
    
    return size() == 0;
}

3.5 search

Call the lastIndexOf method of the parent class to find the element o from the top of the stack, and return its subscript position in the array if found. If it does not return -1.

public synchronized int search(Object o) {
    
    
    int i = lastIndexOf(o);

    if (i >= 0) {
    
    
        return size() - i;
    }
    return -1;
}

Guess you like

Origin blog.csdn.net/gongsenlin341/article/details/108652006