public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { ...... /** * 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 E[] elementData; /** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size; ...... }
ArrayList 的底層最重要的兩個屬性:Object 數組和 size 屬性。java
add方法--ArrayList源碼摘要:數組
public boolean add(E o) { ensureCapacity(size + 1); // Increments modCount!! elementData[size++] = o; return true; }
ensureCapacity方法--ArrayList源碼摘要:dom
public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; } elementData = (E[])new Object[newCapacity]; System.arraycopy(oldData, 0, elementData, 0, size); }
a. ArrayList 是經過將底層 Object 數組複製的方式(System.arraycopy方法)來處理數組的增加;this
b. 當ArrayList 的容量不足時,其擴充容量的方式:先將容量擴充至當前容量的1.5倍,若還不夠,則將容量擴充至當前須要的數量。spa
remove 方法--ArrayList源碼摘要:code
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[index])) { fastRemove(index); return true; } } return false; }
fastRemove 方法--ArrayList源碼摘要:ci
private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work }
private void fastRemove(int index) 可見,ArrayList 的元素移除後,也是經過 Object 數組複製的方式(System.arraycopy方法)來處理數組的變化; size 老是記錄着當前的數組元素的數量。element
這也就解釋了 ArrayList 的特色:增長、刪除和移動元素的效率低(數組複製過程消耗資源較多); 而查找元素和更新元素的效率高。資源
get 方法--ArrayList 源碼摘要:rem
public E get(int index) { RangeCheck(index); return elementData[index]; }
set 方法--ArrayList 源碼摘要:
public E set(int index, E element) { RangeCheck(index); E oldValue = elementData[index]; elementData[index] = element; return oldValue; }