Java Data Structure-Stack and java-stack

Source: Internet
Author: User

Java Data Structure-Stack and java-stack

Stack is a typical data structure, and its elements meet the characteristics of LIFO.

The implementation of Stack in Java inherits from Vector, so it naturally has some Vector features, so Stack is thread-safe.

class Stack<E> extends Vector<E> {

In fact, in addition to the methods inherited from the Vector, Stack only provides five methods:

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

The push function is used to push an element to the top of the Stack, which affects the performance of addElement:

    public synchronized void addElement(E obj) {        modCount++;        ensureCapacityHelper(elementCount + 1);        elementData[elementCount++] = obj;    }

It can be seen that the method is to add an element at the end of the Vector, and its time complexity is o (1 ).

The peek function is used to view the top elements of the stack but is not deleted. Its performance is mainly determined by the elementAt function of Vector:

    public synchronized E elementAt(int index) {        if (index >= elementCount) {            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);        }        return elementData(index);    }    E elementData(int index) {        return (E) elementData[index];    }

Because the bottom layer of the Vector is array implementation, the subscript can be directly located, so the time complexity of peek is o (1 ).

The pop function removes and obtains the top element of the stack. It can be seen in the source code that peek is called to obtain the top element of the stack and removeElementAt is used to delete the top element of the stack, this function is also the key to determining the performance of pop:

    public synchronized void removeElementAt(int index) {        modCount++;        if (index >= elementCount) {            throw new ArrayIndexOutOfBoundsException(index + " >= " +                                                     elementCount);        }        else if (index < 0) {            throw new ArrayIndexOutOfBoundsException(index);        }        int j = elementCount - index - 1;        if (j > 0) {            System.arraycopy(elementData, index + 1, elementData, index, j);        }        elementCount--;        elementData[elementCount] = null; /* to let gc do its work */    }

In my opinion, after an element is deleted, the elements in the array will be copied and adjusted. The time complexity is o (n), but considering the particularity of the passed index value:

Index = elementCount-1;

In this case, the if (j> 0) condition will never be true, because j is always 0, and the operation of copying and adjusting elements in the middle will be avoided, it is just to assign the final value of the Vector to null at the end, and the time complexity is o (1 ).

Search is used to find the index of an element in the Stack. The lastIndexOf function of Vector is used here. The Code is as follows:

    public synchronized int lastIndexOf(Object o) {        return lastIndexOf(o, elementCount-1);    }    public synchronized int lastIndexOf(Object o, int index) {        if (index >= elementCount)            throw new IndexOutOfBoundsException(index + " >= "+ elementCount);        if (o == null) {            for (int i = index; i >= 0; i--)                if (elementData[i]==null)                    return i;        } else {            for (int i = index; i >= 0; i--)                if (o.equals(elementData[i]))                    return i;        }        return -1;    }

We can see that the search process is from forward to forward, and the time complexity must be o (n ).

 

Stack is a subclass of Vector, so the Vector function is also applicable here. We will not repeat it here. It will be included in the introduction Article on Vector.

Stack is thread-safe, so its performance will inevitably be affected. To use a non-thread-safe Stack, you can directly use the rollback list. The methods provided by the rollback list itself include Stack operations.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.