Collection Series-arraylist Source analysis

Source: Internet
Author: User
Tags array length int size
Collection Series-arraylist Source Analysis

This article analyzes the source code of ArrayList, in the analysis before we talk about the array. The array may be one of the earliest data structures we have come into contact with, it is a continuous address space in memory for the storage of elements, because it directly manipulate the memory, so the performance of the array is better than the collection class, which is a big advantage of using arrays.


But we know that the fatal flaw in the array is that the array size must be specified at initialization time, and the size of the array cannot be changed in subsequent operations. What we encounter more in reality is that we don't know how many elements to store at first, but we want the container to automatically expand its own capacity so that more elements can be stored.


ArrayList is able to meet this requirement, and it can automatically scale to accommodate the increasing storage elements. Its bottom layer is based on an array, so it has some of the features of an array, such as finding modifications quickly and inserting deletions slowly. In this article we will go deep into the source to see how it is the array of packaging. First look at its member variables and the three main constructors.

Default initialization capacity
private static final int default_capacity = 10;

Empty Object array
private static final object[] Empty_elementdata = {};

Array of objects
Private transient object[] elementdata;

Number of collection elements
private int size;

Construction method for incoming initial capacity
Public ArrayList (int initialcapacity) {
Super ();
if (Initialcapacity < 0) {
throw new IllegalArgumentException ("illegal Capacity:" + initialcapacity);
}
Creates a new array of type object of the specified capacity
This.elementdata = new Object[initialcapacity];
}

Construction method with no parameters
Public ArrayList () {
Super ();
Pass an empty array instance to Elementdata
This.elementdata = Empty_elementdata;
}

Constructing methods for incoming external collections
Public ArrayList (collection<? extends e> c) {
Holds a reference to an internal array of incoming collections
Elementdata = C.toarray ();
Update collection element number size
size = Elementdata.length;
Determines the type of array referenced and converts the reference to an object array reference
if (Elementdata.getclass ()!= object[].class) {
Elementdata = arrays.copyof (elementdata, size, object[].class);
}
}


You can see that ArrayList's internal storage structure is an object-type array, so it can hold elements of any type. When you construct ArrayList, if you pass in the initial size, it creates a new object array of the specified capacity, and if you do not set the initial size, it will not allocate the memory space but use an empty object array, and then allocate the memory when the element is actually placed. The next look at its additions and deletions to check the method.

Increase (ADD)
Public boolean Add (E e) {
Before adding, check if you need to expand the array, at which point the length of the array is minimal size+1
Ensurecapacityinternal (size + 1);
To add an element to the end of an array
elementdata[size++] = e;
return true;
}


Add (Insert)
public void Add (int index, E element) {
Insert Position Range Check
Rangecheckforadd (index);
Check if expansion is required
Ensurecapacityinternal (size + 1);
Move the element behind the insertion position
System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index);
Assign a new value to the location you want to insert
Elementdata[index] = element;
size++;
}

By deleting
Public E-Remove (int index) {
Index cannot be greater than size
Rangecheck (index);
modcount++;
E OldValue = elementdata (index);
int nummoved = size-index-1;
if (nummoved > 0) {
Move the elements behind the index forward one
System.arraycopy (Elementdata, index+1, Elementdata, Index, nummoved);
}
null reference
Elementdata[--size] = null;
return oldValue;
}

Change
Public E Set (int index, E element) {
Index cannot be greater than size
Rangecheck (index);
E OldValue = elementdata (index);
Replace for new element
Elementdata[index] = element;
return oldValue;
}

Check
Public E get (int index) {
Index cannot be greater than size
Rangecheck (index);
Returns the specified position element
Return Elementdata (index);
}


Each time you add an element to the collection, you check that the capacity is sufficient, otherwise the expansion will be in the details below. We first look at specific additions and deletions to check the place to pay attention to.

Add: Just add this element to the end. Fast operation.

Add (Insert): The operation is slower because it needs to move the elements behind the insertion position and involves copying the array.

Delete: Because you need to move the elements behind the deletion position forward, you will also design array replication, so the operation is slower.

Change: Directly to the specified location elements to modify, does not involve elements of mobile and array replication, fast operation.

Check: Directly returns the array element of the specified subscript, which is quick to operate.


Through the source to see, because the search and modify the direct positioning to the array subscript, does not involve elements to move and group replication so faster, and insert Delete due to the moving elements, involving array replication, slow operation. And it is possible to increase the array capacity each time you add an operation, which can also affect performance. Let's take a look at how ArrayList is dynamically expanding.

private void ensurecapacityinternal (int mincapacity) {
If this is still an empty array
if (Elementdata = = Empty_elementdata) {
and default capacity comparisons, take larger values
mincapacity = Math.max (default_capacity, mincapacity);
}
The array has already been initialized to perform this step
Ensureexplicitcapacity (mincapacity);
}

private void ensureexplicitcapacity (int mincapacity) {
modcount++;
Amplification array If the minimum capacity is greater than the array length
if (Mincapacity-elementdata.length > 0) {
Grow (mincapacity);
}
}

Set Maximum Capacity
private static final int max_array_size = integer.max_value-8;

Increase the length of an array
private void Grow (int mincapacity) {
Gets the original capacity of the array
int oldcapacity = Elementdata.length;
The capacity of the new array, increased by half on the original base
int newcapacity = oldcapacity + (oldcapacity >> 1);
Verify that the new capacity is less than the minimum capacity
if (Newcapacity-mincapacity < 0) {
newcapacity = mincapacity;
}
Verify that the new capacity exceeds the maximum array capacity
if (Newcapacity-max_array_size > 0) {
newcapacity = hugecapacity (mincapacity);
}
Copy the original array to the new array
Elementdata = arrays.copyof (Elementdata, newcapacity);
}


The Ensurecapacityinternal method is called to perform a collection capacity check before each element is added. Within this method, the inner array of the current collection is checked for an empty array, and a new object array with a default size of 10 is created. If it is not proved that the current collection has already been initialized, then call the Ensureexplicitcapacity method to check whether the current array capacity satisfies the minimum required capacity and call the Grow method for expansion if it is not satisfied.


As you can see inside the Grow method, each expansion is half the length of the original array, and the expansion is actually creating a larger, larger array, copying the elements of the original array to the new array, and then discarding the original array and using the new array instead. So far, we have analyzed the more commonly used methods in ArrayList, some noteworthy points:

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.