Analysis of JDK1.8-based ArrayList, jdk1.8arraylist

Source: Internet
Author: User

Analysis of JDK1.8-based ArrayList, jdk1.8arraylist
Preface

This article is based on the ArrayList of JDK1.8. This article analyzes the data structure of ArrayList from the following aspects:

  • Constructor
  • Add Method
  • Resizing
  • Remove Method

 

(1) constructor
 1 /** 2  * Constructs an empty list with the specified initial capacity. 3  * 4  * @param  initialCapacity  the initial capacity of the list 5  * @throws IllegalArgumentException if the specified initial capacity 6  *         is negative 7  */ 8 public ArrayList(int initialCapacity) { 9     if (initialCapacity > 0) {10         this.elementData = new Object[initialCapacity];11     } else if (initialCapacity == 0) {12         this.elementData = EMPTY_ELEMENTDATA;13     } else {14         throw new IllegalArgumentException("Illegal Capacity: "+15                                            initialCapacity);16     }17 }18 19 /**20  * Constructs an empty list with an initial capacity of ten.21  */22 public ArrayList() {23     this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;24 }

Summary, the bottom layer of ArrayList is an array

Let's first look at the second constructor, that is, the non-argument Constructor (row 22nd), and assign the default null array to the Object array. After this execution, an empty array is allocated to the heap.

Let's look at the first constructor, which has a parameter constructor.

1/** 2 * we have such a piece of code 3 */4 List <String> list = new ArrayList <> (10 );

The constructor has three branches. initialCapacity is greater than 0, equal to 0, and less than 0. We can see that the value is greater than 0, and the other two can understand the code.

It will directly construct an array of objects with initialCapacity as the size.

 

(2) add Method
 1 /** 2  * Appends the specified element to the end of this list. 3  * 4  * @param e element to be appended to this list 5  * @return <tt>true</tt> (as specified by {@link Collection#add}) 6  */ 7 public boolean add(E e) { 8     ensureCapacityInternal(size + 1);  // Increments modCount!! 9     elementData[size++] = e;10     return true;11 }

The size field is the length of the array. Then enter the ensureCapacityInternal method.

1 private void ensureCapacityInternal(int minCapacity) {2     if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {3         minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);4     }5 6     ensureExplicitCapacity(minCapacity);7 }

It can be seen that the second line is to determine whether the first add, that is, initialization. If the array bit is empty, DEFAULT_CAPACITY is 10.

Initialization is complete, that is, opening an array of 10 objects.

1 private void ensureExplicitCapacity(int minCapacity) {2     modCount++;3 4     // overflow-conscious code5     if (minCapacity - elementData.length > 0)6         grow(minCapacity);7 }

MinCapacity is the number of elements in the list. For example, if the number is put for the first time, that is, 0, elementData. length is the length of the array, that is, 10.

Then the subtraction result is-10. If it is not set, it will not be resized. If it is set, it will be resized.

1 elementData[size++] = e;

Then return the add method and execute this statement. Now, the add method is executed (no expansion );

 

(3) resizing
1/** 2 * assume that the capacity of the list array is 10 for the first expansion, and the minCapacity passed in is 11 3 * oldCapacity is 10 4 * newCapacity is 10 + (10/2) = 15, that is, resizing 1.5 times 5 * There are two if extreme value judgments, read the code very easily and then understand 6 * and then execute Arrays. copy Method 7 */8 private void grow (int minCapacity) {9 // overflow-conscious code10 int oldCapacity = elementData. length; 11 int newCapacity = oldCapacity + (oldCapacity> 1); 12 if (newCapacity-minCapacity <0) 13 newCapacity = minCapacity; 14 if (newCapacity-MAX_ARRAY_SIZE> 0) 15 newCapacity = hugeCapacity (minCapacity); 16 // minCapacity is usually close to size, so this is a win: 17 elementData = Arrays. copyOf (elementData, newCapacity); 18}

I have read the copy method of Arryas. You can check the source code.

So far, the add method of ArrayList has been introduced, and the grow method has been completed.

(4) remove Method
1/** 2 * There are two remove methods in total. One is to delete by index, the other is to delete by element, which is similar to the other. 3 * Delete by index, see note 4 */5 public E remove (int index) {6 // first check whether the value is out of bounds 7 rangeCheck (index); 8 9 modCount ++; 10 E oldValue = elementData (index); 11 12 int numMoved = size-index-1; 13 // move all the following values to the front, System. arraycopy is an native METHOD 14 if (numMoved> 0) 15 System. arraycopy (elementData, index + 1, elementData, index, 16 numMoved); 17 // then the last position is null, gc automatically recycles 18 elementData [-- size] = null; // clear to let GC do its work19 20 return oldValue; 21}

The remove method is simple. Just read the comments I wrote.

(5) Summary

I was drunk after writing for more than two hours. I am debugging the debug of eclipse. My debugging is a bit problematic. The eclipseEE version is okay.

In fact, I have some doubts. I hope you can give me the following answers.

The initialization constructor does not assign a value to the size, that is, it is null. It cannot be directly output or used (an error is reported and has been tested)

However, when the list. size () method is called, the returned value is 0, and no error is reported. I did not see when the value is assigned by debug.

I hope you can answer this article. Thank you.

------------------------------- Gorgeous split line ----------------------------

So tired.

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.