ArrayList Realization Principle
Reprint: http://wiki.jikexueyuan.com/project/java-collection/arraylist.html ArrayList Overview
ArrayList can be understood as a dynamic array, as in MSDN, a complex version of array. Its capacity can grow dynamically compared to an array in Java. ArrayList is the implementation of a variable array of the List interface. All optional list operations are implemented and all elements, including NULL, are allowed. In addition to implementing the list interface, this class provides methods to manipulate the size of an array that is used internally to store lists. (This class is roughly equivalent to the Vector class, except that this class is not synchronized.) )
Each ArrayList instance has a capacity, which is the size of the array used to store the list elements. It is always at least equal to the size of the list. As you add elements to the ArrayList, the capacity increases automatically. Automatic growth will result in a new copy of the data to the array, so if you can predict the amount of data, you can specify its capacity when constructing ArrayList. Before adding a large number of elements, the application can also use the Ensurecapacity action to increase the capacity of the ArrayList instance, which reduces the number of incremental redistribution.
Note that this implementation is not synchronized. If more than one thread accesses a ArrayList instance at the same time, and at least one of the threads modifies the list from the structure, it must maintain an external synchronization. (Structural modification means any action that adds or deletes one or more elements, or explicitly adjusts the size of the underlying array; only the value of the element is not a structural modification.) )
We can understand its application better by studying its internal principle of implementation. the realization of ArrayList
For ArrayList, it implements the List interface, the underlying use of the array to save all elements. Its operations are essentially an array of operations. Here we analyze the source code of ArrayList: implemented interface
public class Arraylist<e> extends abstractlist<e>
implements List<e>, Randomaccess, cloneable , java.io.Serializable
{
}
ArrayList inherited the abstractlist and realized the List. It is an array queue that provides related additions, deletions, modifications, and traversal functions.
ArrayList implements the Randmoaccess interface, which provides a random access function. Randmoaccess is a list implemented in Java to provide quick access to the list. In ArrayList, we can quickly get the element object by the ordinal of the element, which is the fast random access.
ArrayList implements the Cloneable interface, which covers the function clone () and can be cloned. ArrayList implements the Java.io.Serializable interface, which means that ArrayList supports serialization and can be transmitted through serialization. The bottom layer uses arrays to implement
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*
private transient object[] elementdata;
Construction Method
/** * Constructs a empty list with an initial capacity of ten.
* public ArrayList () { this (10);
&NBSP /** * Constructs a empty list with the specified initial. * * @param initialcapacity the Initial capacity of the list * @thr OWS IllegalArgumentException If the specified initial capacity * is negative & nbsp
* public ArrayList (int initialcapacity) { super (); if (initialcapacity < 0) throw New illegalargument Exception ("Illegal Capacity:" + &NBSP ;
initialcapacity); this.elementdata = new Object[initialcapacity]; &NBSP /** * Constructs a list containing the elements of the specified &NBS P
* collection, in the order they are returned by the collection ' s * iterator. * * @param c the collection whose elements are to is placed into this list * @ Throws NullPointerException if the specified collection is null / public ArrayList (collectio n<?
Extends e> c) { elementdata = C.toarray ();
size = elementdata.length; //C.toarray might (incorrectly) not return object[] (6260652) if (Elementdata.getclass ()!= object[].class) elementdata = arrays.copyof (elemen
Tdata, size, object[].class); &NBSP;}
ArrayList provides a three-way constructor:
Public ArrayList () can construct an empty list with a default initial capacity of 10;
The public ArrayList (int initialcapacity) constructs an empty list that specifies the initial capacity;
Public ArrayList (collection<? extends e> c) constructs a list of elements that contain the specified Collection, which are arranged in the order in which they are returned by the Collection iterator. Storage
There are a number of ways to add elements in ArrayList, which are explained here:
1.set (int index, E Element): This method first calls Rangecheck (index) to verify that the index variable is outside the array range and throws an exception. Then, the value of the original index position is taken out, and the new element is placed in the index position and returned to OldValue.
/** * Replaces the element at the specified position in this list with * the S
pecified element. * * @param index of the element to replace * @param element element to B e stored at the specified position * @return The element previously at the specified position &NBSP ; * @throws indexoutofboundsexception {@inheritDoc} / public e set (int index, E element) {&N Bsp
rangecheck (index);
e oldValue = elementdata (index);
elementdata[index] = element;
return OldValue; &NBSP} /** * Checks If the given index is in range. if not, throws a appropriate * runtime exception. this method does *not* Check if the index was * negative:it is always used ImmediAtely prior to a array access, * which throws a arrayindexoutofboundsexception if index is negative
. */ private void Rangecheck (int index) { if (index)
= size) throw new Indexoutofboundsexception (outofboundsmsg (index)); &NBSP;}
2.add (E): This method adds the specified element to the tail of the list. When the capacity is low, the Grow method is invoked to increase capacity.
/** * Appends the specified element to the "end of" this list. * * @param e element to is appended to this list * @return <tt>true</ Tt> (as specified by {@link collection#add}) * public boolean Add (E e) { & nbsp ensurecapacityinternal (size + 1);
//increments modcount!!
elementdata[size++] = e;
return true; &NBSP} private void ensurecapacityinternal (int mincapacity) { modcount++
; //overflow-conscious code &NBSP;IF (mincapacity-elementdata.length) ;
0) grow (mincapacity);
&NBSP} private void grow (int mincapacity) { //overflow-conscious code int oldcapacity = Elementdata.Length
int newcapacity = oldcapacity + (oldcapacity >> 1); if (newcapacity-mincapacity < 0) newcapacity = m
incapacity; if (newcapacity-max_array_size > 0) newcapacity
= Hugecapacity (mincapacity); //mincapacity is usually close to size, so this is a win: &NBSP;ELEMENTD
ATA = arrays.copyof (Elementdata, newcapacity); &NBSP;}
3.add (int index, E Element): Inserts an element at the index position.
/** * Inserts the specified element at the specified position on this * list. Shifts the element currently at this position (if any) and * No subsequent elements to the right (adds one
to their indices). * * @param index index at which the specified element was to inserted * @par am element element to is inserted * @throws indexoutofboundsexception {@inheritDoc} */&nbs P
public void Add (int index, E element) { rangecheckforadd (index); ensurecapacityinternal (size + 1);
//increments modcount!! system.arraycopy (elementdata, index, Elementdata, index + 1, &NBSP ;
size-index);
elementdata[index] = element;
size++; &NBSP;}
4.addAll (collection< extends e> c) and addall (int index, COLLECTION<? extends e> c): Assign a specific The elements in the Collection are added to the end of Arraylist.
/** * Appends all of the elements in the specified collection to the "end of * This list, in The order is they are returned by the * Specified collection ' s iterator. the behavior of this operation are * undefined if the specified collection is modified while the opera tion * is in progress. (this implies so the behavior of this call are * undefined if the specified collection is this list,
And this * The list is nonempty.) * * @param c collection containing elements to is added to this list * @return <tt>true</tt> If this list changed as a and the call * @throws nullpointerexception if T
He specified collection is null / 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; &NBSP} /** * Inserts all of the elements in the specified to this collection P * list, starting at the specified position. shifts the element * Currently at this position (if any) and any subsequent elements to &NBSP ; * The right (increases their indices). the new elements'll appear * in the "order" of They are returned by the
* Specified collection ' s iterator. * * @param index index at which to insert the "I" from the * specified collection * @param c collection conTaining elements to is added to this list * @return <tt>true</tt> If this list changed as Res Ult of the call * @throws indexoutofboundsexception {@inheritDoc} * @throws NULLPOINTEREXCEP tion if the specified collection is null */ public boolean addall (int index, COLLECTION<?
Extends e> c) { rangecheckforadd (index);
object[] A = C.toarray ();
int numnew = a.length; ensurecapacityinternal (size + numnew);
//increments modcount int nummoved = Size-index; if (nummoved > 0) system.arraycopy (Elementdata, in Dex, Elementdata, index + numnew, &NB Sp
nummoved); system. Arraycopy (A, 0, Elementdata, index, numnew);
size + = numnew;
return numnew!= 0; &NBSP;}
In the ArrayList storage method, its core essence is to add elements into the array at a certain location. But it will also involve factors such as insufficient array capacity and growth. Read
This approach is simpler, and the reason why ArrayList can support random access is also obvious because its internal data structure is an array, and the array itself supports random access. The method first determines whether the index value entered is out of bounds, and then returns the element of the index position of the array.
/**
* Returns The element at the specified position into this list.
*
* @param index of the element to return
* @return The element at the specified position in this list
* @throws indexoutofboundsexception {@inheritDoc} * */public
E get (int index) {
Rangecheck (index);
Return (E) elementdata[index];
}
private void Rangecheck (int index) {
if (index >= size)
throw new Indexoutofboundsexception (outofbounds MSG (index));
Remove
ArrayList provides two ways to remove functionality based on subscript or the specified object. Note that the return value for this method is not the same, as follows:
/** * Removes the element at the specified position into this list.
* Shifts any subsequent elements to the "left" (subtracts one from their * indices). * * @param index of the element to be removed * @return the element That is removed from the list * @throws indexoutofboundsexception {@inheritDoc} /
public E Remove (int index) { rangecheck (index);
modCount++;
e oldValue = elementdata (index);
int nummoved = size-index-1; if (nummoved > 0) system.arraycopy (Elementdata, in Dex+1, Elementdata, index, &NB Sp
nummoved); elementdata[--size] = null;
Let GC does its work return OldValue; &NBSP}/** * Removes the occurrence of the specified element from this list, * If it is present. if the does not contain the element, it is * unchanged. more formally, removes the element with the lowest index * <tt>i</tt> such that & nbsp * <tt> (o==null ? get (i) ==null : o.equals (get (i)) </tt> * (if such a element exists). returns <tt>true</tt> If this list * contained the specified element (or equivalently, if
This list * Changed as a, the call). * * @param o element to is removed from this list, if present * @return <tt >true</tt> If this list contained the specified element */ public BooleAn remove (Object o) { if (o = null) { for (int Inde x = 0; index < size; index++) if (elementdata[index] = null) { & nbsp
fastremove (index);
return true; &NBSP, &NBSP} else { for (int index = 0; index < size; index++) if (o.
Equals (Elementdata[index])) { fastremove (index);
return true; &NBSP, } return
False }
Note: Removing an element from an array also causes all elements of the removed element to move one position to the left. Adjust Array capacity
From the code described above for storing elements in ArrayList, we see that whenever an element is added to an array, it checks whether the number of elements added will exceed the length of the current array, and if it is exceeded, the array expands to accommodate the need to add data. Array expansion has two methods, in which developers can increase the capacity of ArrayList by means of a public method ensurecapacity (int mincapacity), while in operations such as storage elements, if there is insufficient capacity, Will invoke the Priavte method private void ensurecapacityinternal (int mincapacity) implementation.
public void ensurecapacity (int mincapacity) { if (mincapacity > 0) &N Bsp
ensurecapacityinternal (mincapacity); &NBSP} private void ensurecapacityinternal (int mincapacity) { modcount+
+; //overflow-conscious code &NBSP;IF (mincapacity-elementdata.length) ;
0) grow (mincapacity); &NBSP} /** * Increases the capacity to ensure this it can hold at least the & nbsp
* Number of elements specified by the minimum capacity argument. * * @param mincapacity the desired minimum capacity / private V OID grow (int mincapacity) { //overflow-conscious code int Oldcapa
City = Elementdata.length; int newcapacity = oldcapacity + (oldcapacity >> 1); if (newcapacity-mincapacity < 0) newcapacity = m
incapacity; if (newcapacity-max_array_size > 0) newcapacity
= Hugecapacity (mincapacity); //mincapacity is usually close to size, so this is a win: &NBSP;ELEMENTD
ATA = arrays.copyof (Elementdata, newcapacity); &NBSP;}