JDK 1.7 ArrayList Source Analysis

Source: Internet
Author: User

1, first look at the ArrayList of the base class have what

public class Arraylist<e> extends abstractlist<e>
Implements List<e>, Randomaccess, Cloneable, java.io.Serializable

Can be summed up as:

ArrayList inherited Abstractlist.

Implementation of List, Rondomacess, cloneable, serializable for the general container will be implemented cloneable for cloning implementation serializable implementation of serialization

2. Variables defined in ArrayList

There are 4 main variables, we need to know some basic information before understanding these variables, the ArrayList is implemented by the array, the initial default capacity is 10,

private static final int default_capacity = ten;//initial default capacity

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

Private transient object[] elementdata;//arraylist the container in which the data is actually stored

private int size;//The number of data in the current array

3. Constructors in ArrayList

There are a total of three constructors in ArrayList, which are constructors with initialization capacity, constructors with no parameters, constructors with set parameters

(1) From the source code we can see that this is just a simple process of creating an array object, but before you create the object, you need to determine whether the initial capacity value is <0

Public ArrayList (int initialcapacity) {
Super ();
if (initialcapacity < 0)
throw new IllegalArgumentException ("Illegal capacity:" +
initialcapacity);
This.elementdata = new Object[initialcapacity];
}

(2) The parameterless constructor, here we need to note that although the default capacity of the array is 10, but without parameters, the initialization of the array is actually an empty array instead of creating an array of size 10
Public ArrayList () {
Super ();
This.elementdata = Empty_elementdata;
}

(3) Set because it is an array operation, arrays.copyof is used for copying and type conversion
Public ArrayList (collection<? extends e> c) {
Elementdata = C.toarray ();
size = Elementdata.length;
C.toarray might (incorrectly) not return object[] (see 6260652)
if (Elementdata.getclass ()! = Object[].class)
Elementdata = arrays.copyof (elementdata, size, object[].class);
}

4, the main function of the analysis of the container generally our common operation is to delete and change

Increase

(1) Add a number of operations, size records the number of the current array of numbers so the actual operation is the array under the index of the size of the assignment, and then size++, but before we have to determine whether the size+1 is out of bounds, that is, the need for expansion, the expansion of our next talk, The return value of the function is a Boolean type

Public Boolean Add (E e) {
Ensurecapacityinternal (size + 1); Increments modcount!!
elementdata[size++] = e;
return true;
}

(2) The operation of adding a number to the specified subscript. Here we need to note that a function is system.arraycopy () this is a common API in ArrayList, mainly used for array shift

The original number exists in elementdata[], a total size object, and now we need to insert a new object in subscript for index, we need to shift the subscript [index, size-1] range of objects to [index+1,size]

Operation is system.arraycopy (Elementdata, index, Elementdata, index + 1,size-index);

(source array, copy start subscript, target array, target array start subscript, copy object number)

Public void Add (int index, E Element) {
Rangecheckforadd (index);

Ensurecapacityinternal (size + 1); Increments modcount!!
System.arraycopy (Elementdata, index, elementdata, index + 1,size-index);
Elementdata[index] = element;
size++;
}

(3) Add a set of operations. First, the collection is converted to an array, and then the System.arraycopy function is called to copy the number in the new array to elementdata[] if the number of objects in the collection needs to be enlarged.

Public Boolean addall (collection<? extends e> c) {
Object[] A = C.toarray ();
int numnew = A.length;
Ensurecapacityinternal (size + numnew); Increments Modcount
System.arraycopy (A, 0, elementdata, size, numnew);
Size + = Numnew;
return numnew! = 0;
}

By deleting

(1) Delete the object labeled Index, first determine whether index is valid, then move forward one copy, the last size subscript position is assigned null, return the deleted object

Public E Remove (int index) {
Rangecheck (index);

modcount++;
E OldValue = elementdata (index);//Here you may wonder why Elementdata (index) is not Elementdata[index] because Elementdata (index) is an intrinsic function of ArrayList, and is actually the object that returns the subscript index.

int nummoved = size-index-1;
if (nummoved > 0)
System.arraycopy (Elementdata, index+1, Elementdata, index,nummoved);//There is another system.arraycopy .... When people ask me what impresses me in ArrayList, that's it.
Elementdata[--size] = null; Clear to let GC do it work

return oldValue;
}

(2) Delete an object operation. In fact, this is a process of passing through the group, in two conditions to traverse, when the deleted object is null, the case can be non-null, from which we can see actually encountered the first qualifying object is returned, so this operation does not delete all

Public boolean remove (Object o){
if (o = = null) {
for (int index = 0; index < size; index++)
if (elementdata[index] = = null) {
Fastremove (index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (O.equals (Elementdata[index])) {
Fastremove (index);
return true;
}
}
return false;
}

(3) Delete the operation of a collection.

Public Boolean RemoveAll (collection<?> c) {
Return Batchremove (c, false);//Call an intrinsic function
}

This function takes advantage of the idea of tow Poit, a read node, a write node, a traversal array that is preserved when the object does not exist in the collection, and the last value of the [w,size] range is null

Private Boolean Batchremove (Collection<?> C, Boolean complement){
Final object[] Elementdata = this.elementdata;
int r = 0, w = 0;
Boolean modified = false;
try {
for (; r < size; r++)
if (C.contains (elementdata[r]) = = complement)
elementdata[w++] = Elementdata[r];
} finally {
Preserve behavioral compatibility with Abstractcollection,
Even if C.contains () throws.
if (r! = size) {
System.arraycopy (Elementdata, R,elementdata, w,size-r);
W + = Size-r;
}
if (w! = size) {
Clear to let GC do it work
for (int i = w; i < size; i++)
Elementdata[i] = null;
Modcount + = size-w;
size = W;
Modified = true;
}
}
return modified;
}

Change

(1) Assign a new object to the object at index subscript, first determine whether index is limited, then assign a value to index position on an array, return the old object

Public E Set (int index, e element) {
Rangecheck (index);

E OldValue = elementdata (index);
Elementdata[index] = element;
return oldValue;
}

Check

(1) Find the object labeled Index, first determine whether index is valid, and then return the array labeled index

Public E Get (int index) {
Rangecheck (index);

Return Elementdata (index);
}

Expansion analysis

Above we will call Ensurecapacityinternal (size + 1) before parsing an additional object operation, and now we will go along this line to analyze the expansion process.

private void ensurecapacityinternal (int mincapacity) {
if (Elementdata = = Empty_elementdata) {
mincapacity = Math.max (default_capacity, mincapacity);//maximum value for default capacity and minimum capacity when the current array is empty
}

Ensureexplicitcapacity (mincapacity);//used to compare the current array length and minimum capacity
}

private void ensureexplicitcapacity (int mincapacity) {
modcount++;

Overflow-conscious Code
if (Mincapacity-elementdata.length > 0)//expansion is required when the minimum required capacity is greater than the length of the current array
Grow (mincapacity);
}

Expansion function

private void Grow (int mincapacity) {
Overflow-conscious Code
int oldcapacity = Elementdata.length;
int newcapacity = oldcapacity + (oldcapacity >> 1); This shows that the capacity of the expansion is 1.5 times times the old capacity.
if (newcapacity-mincapacity < 0)//also to compare 1.5 times times the old capacity with the minimum required capacity to take a larger value
newcapacity = mincapacity;
if (newcapacity-max_array_size > 0)
newcapacity = hugecapacity (mincapacity);
Mincapacity is usually close to size, so this is a win:
Elementdata = arrays.copyof (Elementdata, newcapacity);//Create a new newcapacity length an array sets the value of the old array to the new array
}

private static int hugecapacity (int mincapacity) {
if (mincapacity < 0)//Overflow
throw new OutOfMemoryError ();
Return (Mincapacity > Max_array_size)? Integer.MAX_VALUE:MAX_ARRAY_SIZE; From here we can see that the maximum allowable size of the array is Integer.max_value
}

Other commonly used functions

1. Empty function

Public Boolean isEmpty () {
return size = = 0;
}

2, check the current ArrayList in the number of objects

public int size () {
return size;
}

3. Does it contain an object?

Public Boolean contains (Object o) {
return IndexOf (O) >= 0;
}

is also divided into null and non-null to traverse

public int indexOf (Object o){
if (o = = null) {
for (int i = 0; i < size; i++)
if (elementdata[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (O.equals (Elementdata[i]))
return i;
}
return-1;
}

4, reduce the capacity of space

Public void TrimToSize () {
modcount++;
if (Size < Elementdata.length) {
Elementdata = arrays.copyof(elementdata, size); Creates a new array of size sizes and assigns the values of the old array to the new array
}
}

Summary: The ArrayList is an array implementation, the default initialization capacity is 10, the expansion rule is 1.5 times times the length of the old array and the minimum capacity of the current required maximum value, the most commonly used operations are arrays.copyof () and System.arraycopy ()

JDK 1.7 ArrayList 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.