1 /**2 * The array buffer into which the elements of the ArrayList are stored.
3 * The capacity of the ArrayList is the length of this array buffer.
4*/
5 private transientObject[] elementData;6
7 /**8 * The size of the ArrayList (the number of elements it contains).
9 *
10 *@serial11*/
12 private int size;
从这里看出, ArrayList是用Array来实现的,包括elementData数组和其大小两个属性。
1 public booleanadd(E e) {2 ensureCapacity(size + 1); //Increments modCount!!
3 elementData[size++] =e;4 return true;5 }
/*** Increases the capacity of this ArrayList instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
*@paramminCapacity the desired minimum capacity*/
public void ensureCapacity(intminCapacity) {
modCount++;int oldCapacity =elementData.length;if (minCapacity >oldCapacity) {
Object oldData[]=elementData;int newCapacity = (oldCapacity * 3)/2 + 1;if (newCapacity
newCapacity=minCapacity;//minCapacity is usually close to size, so this is a win:
elementData =Arrays.copyOf(elementData, newCapacity);
}
}
ensureCapacity ensure that the inner array size satisfy the add(Object o) operation. If minCapacity is bigger than the original array size, it increase the array size and do the checking again. ensureCapacity() will increase the array size by at least 1. After the array size is OK, copy original array into new array with bigger size. After ensureCapacity() is returned, set elementData[size] to be the newly added element. Since the array size is increased by at least one. call elementData[size] will not throw exception.
public E remove(intindex) {
RangeCheck(index);
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 do its work
returnoldValue;
}
1 /**
2 * Checks if the given index is in range.3 */
4 private void RangeCheck(intindex) {5 if (index >=size)6 throw newIndexOutOfBoundsException(7 "Index: "+index+", Size: "+size);8 }
Remove(int index):
Check if index is out of range. Store the removed object. Move all elements after index one position forward. Mark element of size-1 to be null.