本文基於jdk1.8來分析ArrayList的源碼
首先是主要的成員變量。
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
其中初始大小爲10,size表示集合中元素的個數。此外,還有兩個空數組EMPTY_ELEMENTDATA,和DEFAULTCAPACITY_EMPTY_ELEMENTDATA。通過DEFAULTCAPACITY_EMPTY_ELEMENTDATA的註釋,我們可以瞭解到,這個變量區別於EMPTY_ELEMENTDATA,主要是爲了決定第一個元素插入時,擴容多大的問題。從這裏的描述可以理解到,ArrayList創建好後,其實並沒有真正分配數組空間,而是在第一個元素插入時,才分配的空間。這一點是區別於jdk1.6的。在jdk1.6中,ArrayList一創建,數據空間就默認分配好了,10個或指定的空間。jdk1.8這麼做,可以做到空間延遲分配,提高程序性能。
接下來看一下構造函數。
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
無參構造函數,將創建一個長度爲0的空數組。
有參構造函數,參數大於0時正常創建數組,參數爲0時,也是創建長度爲0的數組。但它和無參構造函數創建的空數組是可以區別開的,它們使用了不同的對象。
接下來是插入元素add。
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
通過calculateCapacity函數,我們可以知道,如果是用new ArrayList()創建的list,第一次add元素,計算得minCapacity = 1。如果是new ArrayList(0)創建的list,計算得minCapacity = 10. 然後再根據minCapacity去grow。
get方法比較簡單,這裏不再分析。
ArrayList的一個常見問題是ConcurrentModificationException,同步修改異常,也稱爲快速失敗,fast-fail。當我們以foreach方式遍歷ArrayList時,如果在遍歷過程中刪除ArrayList的元素,或者別的線程往ArrayList中添加元素,就會拋出該異常。這裏需要注意,以for(int i = 0; i < list.size(); i++)的方式遍歷ArrayList時,是不會拋出同步修改異常的,但用這種方式遍歷,需要處理好i的前進速度。
那麼,用foreach方式遍歷ArrayList爲什麼會拋出同步修改異常呢?
foreach代碼的底層實現,是用iterator對ArrayList進行遍歷,在遍歷過程中,會持續調用next獲取下一個元素。next方法中,會首先checkForComodification(),它的作用是檢查modCount和expectedModCount是否相等。不相等時,則拋出同步修改異常。那麼什麼情況下修改次數和期望修改次數不相等呢?這裏需要首先弄明白,modCount和expectedModCount是什麼東西?modCount是ArrayList從它的父類繼承來的屬性,記錄了集合的修改次數,add,remove時都會給modCount加1. expectedModCount是迭代器的成員變量,它是在創建迭代器時,取的modCount的值,並且,在遍歷過程中不再改變。那麼就清楚了,expectedModCount其實是開始遍歷時modCount的值,如果在遍歷過程中,ArrayList進行了add或remove操作,那麼必然導致expectedModCount和modCount不相等,於是就拋出了同步修改異常。
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
那麼,同步修改異常如何避免呢?或者說,我們如何遍歷集合並把其中的某些元素刪除呢?
答案是使用迭代器的remove方法刪除元素。在迭代器的remove方法中,刪除元素後,會重新把modCount賦值給expectedModCount,所以,它不會拋出同步修改異常。
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}