Collection Family List (five): Stack

Stack is a last-out stack structure, which does not directly implement specific logic, but by inheriting Vector class, calling methods realization Vector class.

public
class Stack<E> extends Vector<E>

The core method

Stack class code is very simple, which the core has three methods: push, pop, peek.

push

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

    return item;
}

You can see the push method called directly addElement methods of Vector element into the end of the array.

pop

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

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

    return obj;
}

pop method calls removeElementAt methods of Vector, delete an element. Note that, remove the last element of the array, rather than the first element.

peek

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

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

peek method returns the last element of the list.

to sum up

Stack method code is really very simple, utilizing Vector implements a thread-safe stack structure. Overall, it has the following characteristics:

  • Vector underlying the use of implementation, so it also uses an array to achieve, but also thread-safe.
  • Last-out stack structure

Guess you like

Origin www.cnblogs.com/chanshuyi/p/java_collection_05_stack.html
Recommended