JDK1.8 ArrayList in the realization of the principle and source code analysis

I. Overview

             ArrayList Java is used in the development of a more frequent class, through the interpretation of the source code, we can understand the internal structure and implementation of ArrayList, clear its advantages and disadvantages, so that we can utilize during programming.

Second, source code analysis

2.1 class structure

 ArrayList class structure definition JDK1.8 source as follows:

public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
其中:

List interface implements a queue array has a basic CRUD List function
realizes the functions of the random access RandomAccess interface can
achieve Cloneable interface can be cloned
implements Serializable interface and rewrite the serialization and deserialization method, ArrayList that may have better performance serialization
2.2 member variables and several construction methods 

/ **
* defining serialization ID, primarily to denote different versions compatibility
* /
Private Long serialVersionUID = Final static 8683452581122892189L;

/ **
* default storage capacity of the array (an array of structures underlying the ArrayList)
* /
Private static Final 10 DEFAULT_CAPACITY = int;

/ **
* specified array capacity is zero when using the constant values
* /
[] = {} Private static EMPTY_ELEMENTDATA Final Object;

/ **
* constant values using the default constructor parameter space
* /
Final static Object Private [] = {} DEFAULTCAPACITY_EMPTY_ELEMENTDATA;

/ **
array of objects * real storage of data, transient identifier is not serialized
* /
transient Object [] elementData of; // Simplify to non-nested class Private Access

/ **
* real number of elements in the array, which is less than or equal to elementData.length
* /
Private int size;
/ **
* modification number
* /
protected ModCount transient int = 0;

/ *
* a constructor: specifies the size of capacity
* @param initialCapacity
* /
public the ArrayList (int initialCapacity) {
/ *
* specifies how much capacity how much capacity is
* /
IF (initialCapacity> 0) {
this.elementData = new new Object [initialCapacity];
} the else IF (initialCapacity == 0) {// capacity size is not specified, an empty array
this.elementData = EMPTY_ELEMENTDATA;
} {the else
the throw new new an IllegalArgumentException ( "Illegal Capacity:" +
initialCapacity);
}
}

/ **
* constructor II: empty default reference constructor
* /
public the ArrayList () {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

/**
* 构造函数三:传入集合参数的构造函数
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
elementData = ((ArrayList<?>) c).toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
2.3 常用方法

ArrayList element was added to: add (E e) and related methods
/ **
* The specified appends to The End of the this Element List.
*
* @Param E Element to BE the Appended to the this List
* @return <TT> to true </ TT> (AS specified by the Add {@link Collection #})
* /
public Boolean the Add (E E) {
ensureCapacityInternal (size +. 1); // Increments ModCount !!
elementData of [size ++] = E;
return to true;
}
Private void ensureCapacityInternal (int be minCapacity) {
/ **
* If the original number of empty array, then comparing the added number of default (10) comparing, whichever is greater
* /
IF (== elementData of DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
be minCapacity = Math.max (DEFAULT_CAPACITY, be minCapacity);
}

ensureExplicitCapacity (be minCapacity);
}
void ensureExplicitCapacity Private (int be minCapacity) {
ModCount ++;

/ **
* determine the number of elements in the array plus the length of the real length of the array and the current magnitude relationship after 1, is less than 0, returns, if more than 0, then
* call grow (minCapacity) Method
* /
IF (be minCapacity - elementData.length> 0)
Grow (be minCapacity);
}
/ **
* Increases The Capacity to that Ensure® IT CAN Least The HOLD AT
* Number of Elements The Minimum Capacity specified by argument.
*
* @param be minCapacity Desired Minimum capacity the
* /
Private void Grow (int be minCapacity) {
// overflow-Conscious code
int = oldCapacity elementData.length;
int = oldCapacity newCapacity + (oldCapacity >>. 1); // capacity becomes 1.5 times the original
if ( newCapacity - minCapacity <0)
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);
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]>
newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
分析: 

ensureCapacityInternal (size + 1) method, in which method first determines whether the current array is empty array, the comparator comparing the number if the number is added to the default (10), whichever is greater, otherwise calls the second method.
ensureExplicitCapacity (int minCapacity) method, in which the first is modCount + 1, determines the number of array elements plus the true length of the current array lengths after the magnitude relation 1, if less than 0, returns, if more than 0, the method is called 3 .
grow (minCapacity) method using oldCapacity + (oldCapacity >> 1) is the length of the current array becomes 1.5 times the original, and then compared with the upper limit value of longitudinal expansion after expansion, then calls Method 4.
Arrays.copyOf (elementData, newCapacity) method, the method is to call the underlying System.arraycopy (original, 0, copy, 0,
                         after Math.min (original.length, newLength)) method, the old data is copied to data expansion inside the new array, and returns the new array
and then add a new element is assigned to size after expansion inside the + 1 position.
   To specify the position of the insertion element add (int idnex, E element)
source as follows:

void the Add public (int index, E Element) {
rangeCheckForAdd (index);

ensureCapacityInternal (size +. 1); // Increments ModCount !!
System.arraycopy (elementData of, index, elementData of,. 1 + index,
size - index);
elementData of [ index] = Element;
size ++;
}
can be seen from the source substantially coincides with add (E e) method, the main difference is to increase the line of code: System.arraycopy (elementData, index, elementData , index + 1, size - index), and the index data after the start position from a full copy of the start position of index + 1, and then new data is added in the index position, and before the data need not be moved. (Comparative consumption performance of these actions)

java.lang.System.arraycopy (Object src, int srcPos, Object dest, int destPos, int length), parameters are as follows:

(Original array start position, start position, the target array, the array of the original target array, the number of copies)

Removed (removing subscript elements and removed as according to)
the source code follows:

E Remove public (int index) {
rangeCheck (index);
times // record modified
ModCount ++;
E = elementData of oldValue (index);
// Get the number of elements to be moved
int size = numMoved - index -. 1;
IF (numMoved > 0)
System.arraycopy (elementData of,. 1 + index, elementData of, index,
numMoved);
// assign the element size-1 position is null, GC facilitate recovery
elementData of [- size] = null;


return oldValue;
}
Remove Boolean public (Object O) {
IF (O == null) {
for (int index = 0; index <size; index ++)
IF (elementData of [index] == null) {
fastRemove (index);
return to true;
}
} {the else
for (int index = 0; index <size; index ++)
IF (o.equals (elementData of [index])) {
fastRemove (index);
return to true;
}
}
return to false;
}
Remove a method is exactly the reverse operation and add, remove one element, it will affect the number of digits position, it is also more consumption performance. The core code is called java.lang.System.arraycopy (Object src, int srcPos, Object dest, int destPos, int length) method

Query
public GET E (int index) {
/ **
* Check if bounds
* /
rangeCheck (index);
/ **
* returns the specified position on the element
* /
return elementData of (index);
}
// access operation position

@SuppressWarnings ( "an unchecked")
E elementData of (int index) {
return (E) elementData of [index];
}
modify
public E SET (int index, E Element) {
/ **
* check if bounds
* /
rangeCheck (index);
/ **
* Get the old value of the element
* /
E = elementData of oldValue (index);
/ **
* new assignment element
* /
elementData of [index] = element;
/ **
* returns the old value of the element
* /
return oldValue;
}
Clear Method
public void Clear () {
ModCount ++;

// each element to null, the convenience gc recovery
for (int I = 0; I <size; I ++)
elementData of [I] = null;

size = 0;
}
 if comprising
public Boolean the contains (Object O) {
return the indexOf (O)> = 0;
}
public int the indexOf (Object O) {
IF (O == null) {
for (int I = 0; I <size; I ++)
IF ( elementData of [I] == null)
return I;
} the else {
for (int I = 0; I <size; I ++)
IF (o.equals (elementData of [I]))
return I;
}
return -1;
}
this method two cases: null and non-null value traversal, if the query returns to the indexing position, otherwise it returns -1, and then compared with 0, there is greater than 0, less than 0 does not exist.

Third, the summary

      Element efficiency and the efficiency of random access traversal is relatively high, but the added element to specify the location of the array based List implementation or delete the specified position is relatively low.
---------------------

Guess you like

Origin www.cnblogs.com/ly570/p/11257592.html