Reference Links:
Java collections, ArrayList underlying implementations and principles
ArrayList source analysis (based on JDK1.6)
Java Collection Source Analysis (i) ArrayList
"Java Collection Source analysis" ArrayList source analysis
Learn the ArrayList of the source code, first understand the concept of several words: Linear table, array.
Linear table is the most basic, simplest and most commonly used data structure. The relationship between data elements in a linear table is one-to-one, that is, other data elements are end-to-end, except for the first and last data elements.
There are two ways to store a linear table:
-One is sequential storage structure (it can be understood that memory is continuously allocated together)
-The other is a chain-type storage structure (the memory distribution is discontinuous, connected by elements)
arrays, which are a typical sequential storage structure, are characterized by reference to the array of spaces that are contiguous. The fixation of the capacity. When you are unsure of the number of elements, the array you open must be able to put down the maximum number of elements, unfortunately, if the actual quantity is much less than the maximum number, the memory you open in the array will only be wasted. Not conducive to modification. The time complexity of inserting and deleting is the worst possible to achieve O (n), if you insert an element in the first position, you need to move each element of the array back one bit, and if you delete an element in the first position, you need to move each element of the array forward one bit. Facilitate inquiries. The advantage of this storage approach is that the query has a time complexity of O (1), which can be accessed directly through the first address and offset.
Summary of the analysis of the online collection source code is generally to see the class of inheritance and class implementation interface list, arrarylist inside is relatively simple.
ArrayList's internal layout diagram
Here are some ways to explain the ArrayList in JDK1.6 's source code.
Package java.util; public class ArrayList extends Abstractlist implements List, Randomaccess, cloneable, java.io.Serializable {/
/serial version number private static final long serialversionuid = 8683452581122892189L;
ArrayList is based on the array implementation, using the array to save the data private transient object[] elementdata;
Number of actual data in ArrayList private int size;
ArrayList a constructor with capacity size.
Public ArrayList (int initialcapacity) {super ();
if (initialcapacity < 0) throw new illegalargumentexception ("illegal Capacity:" + initialcapacity);
Creates a new array this.elementdata = new object[initialcapacity]; }//ArrayList parameterless constructor.
The default capacity is 10.
Public ArrayList () {this (10); //Create a ArrayList public ArrayList containing Collection (collection< extends e> c) {elementdata = c.t
Oarray ();
size = Elementdata.length;
if (Elementdata.getclass ()!= object[].class) Elementdata = arrays.copyof (elementdata, size, object[].class);
///Set the current capacity value to the actual number of elements public void TrimToSize () {modcount++;
int oldcapacity = Elementdata.length;
if (Size < oldcapacity) {Elementdata = arrays.copyof (elementdata, size);
}//Determine the capacity of the arrarlist.
If ArrayList capacity is not sufficient to accommodate all current elements, set//New capacity = "(Original capacity x3)/2 + 1" public void ensurecapacity (int mincapacity) {
Will "revise statistics" +1, this variable is mainly used to realize the fail-fast mechanism of the modcount++;
int oldcapacity = Elementdata.length; If the current capacity is insufficient to accommodate the current number of elements,//Set the new capacity = "(Original capacity x3)/2 + 1" if (Mincapacity > oldcapacity) {obje
CT olddata[] = elementdata;
int newcapacity = (oldcapacity * 3)/2 + 1;
If it is not enough, set the mincapacity directly to the current capacity if (Newcapacity < mincapacity) newcapacity = mincapacity; Elementdata = arrays.copyof (Elementdata, NewcapaCity); }///Add element E public boolean add (e e) {//Determine the capacity size of the ArrayList ensurecapacity (size + 1) ;
Increments modcount!!
Add e to arraylist elementdata[size++] = e;
return true;
//Returns the actual size of ArrayList public int size () {return size;
}//ArrayList contains Object (O) Public boolean contains (object o) {return indexOf (O) >= 0;
}//Returns whether ArrayList is an empty public boolean isempty () {return size = = 0; //forward lookup, return element's index value 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; //Reverse lookup (find from end of array), returnThe index value of the back Element (o) is public int lastindexof (Object o) {if (o = = null) {for (int i = size-1; I >= 0;
i--) if (elementdata[i]==null) return i;
else {for (int i = size-1 i >= 0; i--) if (O.equals (elementdata[i))
return i;
} return-1;
//Returns the ArrayList Object array public object[] ToArray () {return arrays.copyof (elementdata, size); }//Returns an array of ArrayList elements publict[] ToArray (t[] a) {//If the size of the array a < The number of elements of the ArrayList;/The new Build a t[] array, the size of the array is the number of ArrayList elements,//and copy "ArrayList" to the new array if (A.length < size) return (
T[]) arrays.copyof (elementdata, size, A.getclass ());
If the size of the array a >= the number of ArrayList elements,//The entire elements of ArrayList are copied to array a.
System.arraycopy (elementdata, 0, a, 0, size); if (a.length > Size) a[size] = null;
return A;
//Gets the element value of the index position public E get (int index) {rangecheck (index);
Return (E) Elementdata[index];
//Set the value of index position to element public E set (int index, e element) {Rangecheck (index);
E OldValue = (e) elementdata[index];
Elementdata[index] = element;
return oldValue; ///Add E to ArrayList public boolean add (E e) {ensurecapacity (size + 1);
Increments modcount!!
elementdata[size++] = e;
return true; ///Add E to ArrayList at the specified location public void Add (int index, E element) {if (Index > Size | | Index <
0) throw new Indexoutofboundsexception ("Index:" +index+ ", Size:" +size); Ensurecapacity (size+1);
Increments modcount!!
System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index);
Elementdata[index] = element; size++;
//Delete the element public E remove (int index) {rangecheck (index) at the ArrayList specified location;
modcount++;
E OldValue = (e) elementdata[index];
int nummoved = size-index-1; if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, index, nummoved)
; Elementdata[--size] = null;
Let GC does its work return oldValue; }//delete arraylist specified element 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[in
DEX])) {fastremove (index);
return true; return false;
}//Quick delete index element private void Fastremove (int index) {modcount++;
int nummoved = size-index-1;
Starting with "index+1", replace the preceding element with the following elements.
if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, Index,
nummoved); Set the last element to null elementdata[--size] = NULL;
Let GC does its work}//Delete element public boolean remove (Object o) {if (o = = null) { for (int index = 0; index < size; index++) if (elementdata[index] = = null) {Fastre
Move (index);
return true;
} else {//convenient ArrayList, find "element o", delete, and return true. for (int index = 0; index < size; index++) if (O.equals (Elementdata[index)) {Fastremo
ve (index);
return true;
return false;
} Clears the ArrayList and sets all elements to null public void clear () {modcount++;
for (int i = 0; i < size; i++) elementdata[i] = null;
size = 0;
///Append collection C to ArrayList public boolean addall (Collection c) {object[] a = C.toarray ();
int numnew = A.length; Ensurecapacity (size + numnew);
Increments Modcount system.arraycopy (A, 0, elementdata, size, numnew);
Size + = Numnew;
return numnew!= 0; ///starting at index position, add collection C to ArrayList public boolean addall (int index, Collection c) {if (Index > Si Ze | |
Index < 0) throw new Indexoutofboundsexception ("index:" + index + ", size:" + size);
Object[] A = C.toarray ();
int numnew = A.length; Ensurecapacity (size + numnew);
increments modcount int nummoved = Size-index; if (nummoved > 0) system.arraycOpy (Elementdata, index, elementdata, index + numnew, nummoved);
System.arraycopy (A, 0, Elementdata, index, numnew);
Size + = Numnew;
return numnew!= 0;
}//Delete all elements between Fromindex and Toindex.
protected void RemoveRange (int fromindex, int toindex) {modcount++;
int nummoved = Size-toindex;
System.arraycopy (Elementdata, Toindex, Elementdata, Fromindex, nummoved);
Let GC does its work int newsize = size-(TOINDEX-FROMINDEX);
while (size!= newsize) elementdata[--size] = null;
private void Rangecheck (int index) {if (index >= size) throw new Indexoutofboundsexception (
"Index:" +index+ ", Size:" +size);
///Clone function Public Object clone () {try {Arraylistv = (ArrayList) super.clone (); Copies all elements of the current ArrayList to v V.elementdata = arrays.copyof (Elementdata, size);
V.modcount = 0;
return v; catch (Clonenotsupportedexception e) {//This shouldn ' t happen, since we are cloneable thro
W new Internalerror (); }//Java.io.Serializable write function//will write the ArrayList "capacity, all element values" to the output stream in private void WriteObject (Java). Io. ObjectOutputStream s) throws java.io.ioexception{//Write out element count, and any hidden stuff I
NT Expectedmodcount = Modcount;
S.defaultwriteobject ();
Writes "The capacity of the array" S.writeint (elementdata.length);
Writes "Each element of the array" for (int i=0; i<size; i++) S.writeobject (elementdata[i));
if (Modcount!= expectedmodcount) {throw new concurrentmodificationexception (); }//java.io.Serializable read function: Read/write according to the writing mode, first read the ArrayList "capacity" and then read "all element values" to the private void Reado Bject (Java.io.ObjectInputStream s) throWS java.io.IOException, ClassNotFoundException {//Read in size, and any hidden stuff S.defaultreado
Bject ();
Reads the ArrayList "capacity" int arraylength = S.readint () from the input stream;
Object[] A = Elementdata = new Object[arraylength];
Reads "All element values" from the input stream for (int i=0; i<size; i++) A[i] = S.readobject (); }
}
Summary:
1, the capacity of the ArrayList constructed by the ArrayList parameterless construction method defaults to 10.
2, when you add elements, you need to determine whether the capacity is large enough, that is, call the Ensurecapacity method, when the capacity is not enough to open up new capacity space, and call the Arrays.copyof () method to copy the elements of the old array into the new array.
3, ArrayList is thread-unsafe, and multithreading requires caution.
4, ArrayList based on an array implementation, you can find the element at the specified location directly through the subscript index, so the lookup is efficient, but every time you insert or delete an element, you need to move the element a lot, inserting the deletion element is inefficient.
5, in the search for a given element index value, and so on, the source code has divided the value of the element into null and NOT NULL two kinds of cases, ArrayList allow the element is null.