Simple operation of Deque in Java

Source:
Disclaimer: If I violate anyone's rights, please contact me and I will delete it.
Welcome experts to spray me

Inheritance

Stack inherits from Vector (vector queue). Since Vector is implemented through an array, this means that Stack is also implemented through an array, not a linked list.
Because Vector is thread-safe, stack is also thread-safe here.

Here is the quote

java.lang.Object
↳     java.util.AbstractCollection<E>
   ↳     java.util.AbstractList<E>
       ↳     java.util.Vector<E>
           ↳     java.util.Stack<E>
public class Stack<E> extends Vector<E> {}

Inheritance diagram

Insert picture description here

API function

Insert picture description here

The constructor creates an empty stack

public Stack() {
}

push() pushes the item to the top of this stack. This is exactly the same as the following effect: addElement(item)

public E push(E item) {
        addElement(item); 
        return item;
    }
The addElement in the vector is the synchronized method
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }

pop() deletes the object at the top of this stack and returns the object as the value of this function, which is a synchronized method

    public synchronized E pop() {
        E       obj;
        int     len = size();

        obj = peek();
        removeElementAt(len - 1);

        return obj;
    }

Peek function: return the top element of the stack without performing the delete operation synchronized method

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

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

empty is the stack empty

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

Find the position of "element o" in the stack: count the synchronized method from the bottom of the stack to the top of the stack

    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/qq_45531729/article/details/111996482