In-depth understanding of Java Collection Series four: ArrayList Source code interpretation

Source: Internet
Author: User

Before starting this chapter, let's start with a brief introduction to the list of things.

A brief introduction to list

With an ordered collection, the user can precisely control the insertion position of each element in the list. The user can access the element based on the integer index of the element (where it is located in the list) and search for the elements in the list. Lists typically allow duplicate elements, and allow for the storage of NULL elements.

A brief introduction to ArrayList

The JDK defines the implementation of the variable size data for the Arraylist:list interface.

The main features are as follows:

1. Orderly

2. Thread is not secure

3. Elements can be repeated

4. can store null value

As the name implies, ArrayList is named because it is internally a variable-sized array storage element, which means that the underlying is a dynamic array.

Explanation of the Add method
list<string> li = new arraylist<string> (); Li.add ("33");

First look at this constructor:

Public ArrayList () {this    ];    }
1 public  ArrayList (int initialcapacity) {2     super (); 3         if (initialcapacity < 0) 4             throw new IllegalArgumentException ("Illegal capacity:" +5                                                initialcapacity); 6     this.elementdata = new object[ Initialcapacity];7     }

This first defines the default initial capacity of 10, and then constructs an array of size 10 elementdata; The Elementdata array is an array of ArrayList underlying elements, and the element is of type object. The source definition of the array is also understood below:

Private transient object[] elementdata;

Then look at the Add method:

1 public void Add (int index, E element) {2     if (Index > Size | | | Index < 0) 3         throw new INDEXOUTOFBOUNDSEXCEP tion (4         "Index:" +index+ ", Size:" +size); 5  6     ensurecapacity (size+1);  Increments modcount!! 7     system.arraycopy (Elementdata, index, Elementdata, index + 1, 8              size-index); 9     Elementdata[index] = ele Ment;10     size++;11     }

1, the 6th line of the expansion of the section after the explanation, the rest is relatively simple, we directly see the 7th line. The System.arraycopy method is called.

2, the first time to see this method a little confused, first to explain the following: System.arraycopy (SRC, Srcpos, dest, destpos, length);

The first parameter represents the array to be copied, and the second parameter indicates that the array is copied from the first element.

The third parameter indicates which array to copy to, and the fourth parameter indicates which element is copied to that array, and the fifth parameter represents the length to be copied.

3, explain this method is very clear, the Add method is to add elements in the array after the position of all the elements (including the location), through the Copy method of copy, all move back one position. Then put the element you want to add to the specified location. Of course, this array may be the original array, or it might be a new array after the 6th line of code is enlarged.

Expansion

Expansion, dynamic expansion, which is the bottom of the ArrayList mentioned above, is implemented by a dynamically changing array.

1 public void ensurecapacity (int mincapacity) {2     modcount++; 3     int oldcapacity = elementdata.length; 4     if (mi Ncapacity > Oldcapacity) {5         Object olddata[] = elementdata; 6         int newcapacity = (oldcapacity * 3)/2 + 1; 7
   
    if (Newcapacity < mincapacity) 8         newcapacity = mincapacity; 9             //mincapacity is usually close to size is a win:10             elementdata = arrays.copyof (Elementdata, newcapacity);     }12     }
   

1, we look at the expansion of the algorithm, that is, on the basis of the old capacity, expand 1.5 times times plus 1. As for why it is such an algorithm, I do not understand. But the JDK developers must have thought in this regard: can not be a one-time expansion too large, will cause the waste of memory space, can not be expanded enough, or the next expansion of the operation will soon come. I suppose it was based on such considerations that the algorithm was designed.

2, after the expansion of the end, is to copy all the elements inside the old array into the new array. And the new array is also referenced by the Elementdata variable.

Explanation of the Remove method

Let's take a look at the source code of the method:

1 Public  E Remove (int index) {2     rangecheck (index); 3  4     modcount++; 5     E oldValue = (E) elementdata[in DEX]; 6  7     int nummoved = size-index-1; 8     if (nummoved > 0) 9         system.arraycopy (Elementdata, index+1, Eleme Ntdata, index,10                  nummoved);     elementdata[--size] = NULL;/Let GC does its work12     return OLDVALUE;14
   }

In fact, the process of the Remove method is relatively simple:

1, the 2nd line of code is used to detect whether the array subscript is out of bounds.

2. Then remove the array element at that location.

3. The Arrycopy method copies all elements after the element to be deleted to one position. (Note that this action is copied first, then pasted).

4, this time the last position of the element is redundant, so the 11th line of processing, set it to null.

Advantages and disadvantages of ArrayList

1, the bottom layer is implemented by the array, convenient for random access.

2, sequential add element performance is relatively high, equivalent to each time in the array to add an element,

3, inserting elements, deleting elements, will involve the copy of the element, that is, call the Arraycopy method, if the copy of the element is more, then this compares the consumption performance.

In summary:The advantage of ArrayList is random access, sequential addition.

In-depth understanding of Java Collection Series four: ArrayList Source code interpretation

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.