Java Collection Stack Source analysis

Source: Internet
Author: User

Welcome reprint, please attach Source:
http://blog.csdn.net/as02446418/article/details/47123581

1. Introduction

Stack is a very important data structure type in data structure, because the last-in-first-out function of the stack is a lot of application scenarios in the actual development. The Java API provides a stack (STACCK) implementation that is simple to use as follows

Import Java. Util. Stack;public class Stacktest {/** * @param args * *public static void Main (string[] args) {//TODO auto-generated method stub stack<string> Stack = new Stack&lt ; String> ();Stack. Add("China");Stack. Add("Japan");Stack. Add("Russia");Stack. Add("England");System. out. println(Stack. Size()+"<="+stack. Capacity());System. out. println(Stack. ElementAt(0));System. out. println(Stack. Get(0));System. out. println(Stack. Peek());System. out. println(Stack. Push("France"));System. out. println(Stack. Pop());System. out. println(Stack. Iterator());System. out. println(Stack. Empty());System. out. println(Stack. IsEmpty());System. out. println(Stack. Search("Russia"));}}
2. Inheritance structure

The Stack class inherits the vector class, and the vector class inherits the Abstractlist abstract class, implements the list interface, the Cloneable interface, the Randomacces interface, and the serializable interface. It is necessary to point out that there are two internal classes Listitr and Itr,itr in the vector, which implements the iterator interface while inheriting the vector, and LISTITR implements the ITR interface while inheriting the Listiterator class.

3. Source code Interpretation

Through the stack class to find the method containing pop (), Peek (), push (object), Search (object), empty () method, other values are inherited from the vector class, through the source can be found that vector has several property values: protected object[] elementdata, protected int elementcount; protected int capacityincrement; private static Final I NT max_array_size = 2147483639; With these properties we can find that the stack bottom is implemented using arrays, Elementdata is used to hold each element in the stack, and Elementcount is used to dynamically save the number of elements, The capacityincrement is used to hold the stack's capacity (typically greater than elementcount), and max_array_size is used to limit the maximum number of values that the stack can hold.

A.removeelementat ()

 Public synchronized void Removeelementat(intParamint) { This. Modcount + =1;if(Paramint >= This. Elementcount)Throw NewArrayIndexOutOfBoundsException (Paramint +">="+ This. Elementcount);if(Paramint <0)Throw NewArrayIndexOutOfBoundsException (Paramint);inti = This. Elementcount-paramint-1;if(I >0) System.arraycopy ( This. Elementdata, Paramint +1, This. Elementdata, Paramint, i); This. elementcount-=1; This. elementdata[ This. elementcount] =NULL; }

The Removeelementat () method is used to remove an element from a position, and it is necessary to indicate the position of the element, which is the vector of the parent of the stack, and through the code we can find that the implementation is first to determine whether the argument is valid and then move all the elements in front of the position back one bit. and the number of elements-1, and finally the original position at the top of the element is set to NULL, thus implementing the deletion of an element of the operation.

B:elementdata (int)

E elementData(int paramInt) {    returnthis.elementData[paramInt];  }

Elementdata (int) returns the specific value of an element in a position, and it is also possible to see that the bottom of the stack is implemented by an array.

C:elementat (int)

publicsynchronizedelementAt(int paramInt) {    ifthis.elementCount)      thrownew" >= "          this.elementCount);    return elementData(paramInt);  }elementAt(int paramInt)首先判断参数是否合法,然后就直接调用elementData(paramInt)返回具体的对象值。

D:peek ()

publicsynchronizedpeek() {    int i = size();    if0)      thrownew EmptyStackException();    return1);  }

Through the source can be found peek () just get the first position of the element value (stack subscript and array consistency is starting from 0, the maximum number of elements-1)

E:pop ()

publicsynchronizedpop() {    int i = size();    Object localObject = peek();    1);    return localObject;  }

The implementation of the POP () method is to get the number of elements of the stack first, then call the Peek () method to get the first element at the top of the stack, then call Removeelementat (int) to delete the top element of the stack, and finally return the value of the element.

F:addelement (E ParamE)

publicsynchronizedvoidaddElement(E paramE) {    this1;    ensureCapacityHelper(this1);    this.elementData[(this.elementCount++)] = paramE;  }

The AddElement (E) method is an important method because it implements the addition of elements. It adds the element first when the Modcount plus 1,ensurecapacityhelper () is mainly used to secure the stack capacity, if the current capacity is called grow () method to increase capacity, if the maximum capacity of the Operation Max_array_ The size throws an exception. The third step is to add the element, that is I add the element to the top of the stack, and the number of elements plus 1;

G:search (Object)

publicsynchronizedintsearch(Object paramObject) {    int i = lastIndexOf(paramObject);    if0)      return (size() - i);    return -1;  }

The method returns the location of the object being found, if it does not exist in return-1, through code to find out how it is implemented, first by using the Lastlindexof (Object) method to return the subscript of the element from the bottom of the stack to the top of the stack, The element's position () is then subtracted by the total number of elements minus the subscript, and returned otherwise-1; (Note that the position returned is the position from the top of the stack to the bottom of the stack, the position of the top element is 1)

h:empty()publicbooleanempty() {    return0);  }

The number of directly returned elements is relative to the 0 comparison, and the size () method returns the number of stack elements by This.elementcount.

4. Other (summary)

Through the source code we can see that the bottom of the vector is an array, indicating that the implementation of the stack is implemented by an array, and then through the operation of arrays to imitate the various functions of the stack. And many of the methods in the source vector are synchronized, that is, thread safety, so it is safe to use in multi-threading, but this will certainly be reduced in efficiency.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Collection Stack Source analysis

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.