ArrayList is a variable-length array implementation of the list interface. Implements all the list interface operations and allows the storage of null values. In addition to not synchronizing, ArrayList is basically equivalent to vector. Almost all methods are synchronized in the vector, but ArrayList only synchronizes WriteObject and ReadObject, others such as Add (Object), remove (int), and so on, are not synchronized.
1. Storage
ArrayList uses an object array to store elements.
Private transient Object elementdata[];
ArrayList implements the Java.io.Serializable interface, where the transient indicates that the attribute does not need to be serialized automatically. The following is a detailed explanation of why this is done in the WriteObject () method.
2.add and remove
public boolean add(Object o)
{
ensureCapacity(size + 1);
// Increments modCount!! elementData[size++] = o;
return true;
}
Notice the Ensurecapacity () method here, which is to ensure that the length of the Elementdata array can accommodate a new element. In the "Automatic variable length mechanism" will be explained in detail.
public Object remove(int index)
{
RangeCheck(index);
modCount++;
Object oldValue = elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved);
elementData[--size] = null; // Let gc do its work return oldValue;
}
The role of Rangecheck () is to conduct boundary checks. Because ArrayList uses an object array to store elements, the following elements need to be moved forward when deleting an element. When you delete an element, only the reference to the element in the Elementdata array is null, and the destruction of the specific object is handled by the garbage collector.
The role of Modcount will be described in the following "synchronization in Iterator ()".
Note: A practical method provided by system is used in the forward Move: Arraycopy (), in this case, you can see that the System.arraycopy () method can operate on the same array, which is a native method, if you are working on the same array, Will first copy from the source part to a temporary array, in the temporary array of elements copied to the target location.