Detailed implementation analysis of Java stack

Source: Internet
Author: User
Brief Introduction

One of our most common data structures is probably stack. In the actual program execution, the method calls the process to be inseparable from the stack. So, in a mature class library, what is the implementation of it? Maybe when we practice, we will try to write a stack of the implementation of play. Here, let's take a closer look at the detailed implementation of the JDK. Stack

If we check the JDK's documentation, we'll find that stack is in the Java.util package. It corresponds to an approximate class diagram as follows:

By inheriting the vector class, the stack class can easily implement its own functionality. Because most of the functionality is already supported within the vector.

Stack inside the main implementation of a few methods:

Method name return type Description
Empty Boolean Determines whether the stack is empty.
Peek E Returns the element at the top of the stack.
Pop E The elements that pop up the top of the stack
Push E Push the elements into the stack
Search Int Returns the distance to the top of the target element closest to the top.

As we have mentioned earlier, by inheriting vectors, a large part of the implementation of the function is covered by the vector. The detailed implementation of the vector we will analyze later. It realizes a lot of auxiliary methods, which brings great convenience to the realization of stack. Now, we follow our own thinking to analyze the specific steps of each method, and then compare with the specific implementation code. Empty

From our point of view, if you want to determine whether stack is empty, you need to have a variable to calculate the length of the current stack, if the variable is 0, then the stack is empty. Or we have a variable that points to the top of the stack, and if it is set to null at the beginning, we can assume that the stack is empty.   This part of the implementation code is also simple: Java code public boolean empty () {return size () = 0; }

If further analysis is possible, the vector has already implemented the size () method. Within the vector there is a variable elementcount to denote the number of elements in the container. A 0 indicates that the container is empty.   This part of the vector is implemented as follows: Java code public synchronized int size () {return elementcount; }

Peek

    Peek refers to the element that returns the top of the stack, and we don't make any changes to the stack itself. If there are elements in the stack, we return to the topmost one. The index of the element is the length of the stack. If the stack is empty, throw the exception: Java code    public synchronized e peek ()  {        int     len = size ();           if  (len == 0)            throw new  emptystackexception ();       return elementat (len - 1);   }  

The

  This elementat method is also an implementation within the vector. Within the vector, it is actually a Elementdata object array to store the elements. So to find the top element is nothing more than access to the top of the stack index. Its detailed implementation is as follows: Java code    public synchronized e elementat (int index)  {       if  (index >= elementcount)  {            throw new arrayindexoutofboundsexception (index +  " > =  " + elementcount);       }           return elementdata (index);  }      @SuppressWarnings ("unchecked")    E elementdata (Int index)  {       return  (E)   elementdata[index];  }   Pop

Pop method is to the top of the stack of elements to bounce out, if there are elements in the stack, take the topmost one, otherwise you will throw the exception: Java code public synchronized e pop () {e obj;          int len = size ();       obj = Peek ();          Removeelementat (len-1);   return obj; }

Here, you can determine if the stack top element is implemented in the Peek method, and the part that throws the exception if the stack is empty is included in the Peek method. One of the important things to note here is that after you get the top element through peek (), we need to remove the topmost element with the Removeelementat () method. We may not be aware of this in peacetime. Why do you want to remove it? We have a elementcount anyway to record the length of the stack, whether it or not it can be.

    Actually, there is a potential memory leak when the program is running. Because in Java, if the type we normally define is a strong reference type. For example, the vector is a strong type of object[for the underlying array to hold the data. When a strong type makes GC in the JVM, it is not recycled as long as it is referenced in the program. That means here, as long as we've been using stack, all the associated elements in the stack don't want to be released. This can lead to a memory leak for a long running time. So, to solve this problem, here is the Removeelementat () method.

  Java code    public synchronized void removeelementat (int index)  {        modCount++;       if  (index >=  Elementcount)  {           throw new  ArrayIndexOutOfBoundsException (index +  " >= "  +                                                       elementcount);            }       else if  (index < 0)  {            throw new arrayindexoutofboundsexception (index);   &Nbsp;   }       int j = elementCount -  index - 1;       if  (j > 0)  {            system.arraycopy (elementdata, index + 1,  ELEMENTDATA,&NBSP;INDEX,&NBSP;J);       }        elementcount--;       elementdata[elementcount] = null; /* to  let gc do its work */  

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.