在Java給咱們提供的各類容器類中,最經常使用的就是ArrayList了吧,你可能早就把它用爛了,但它內部細節是怎麼實現的,數組怎麼動態增加的呢?今天咱們就來看一下ArrayList的源碼一探個究竟。html
本文分析的ArrayList源碼基於JDK 1.8java
首先打開ArrayList類,看一下這個類的定義:數組
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
複製代碼
ArrayList繼承自AbstractList,支持泛型。bash
而後實現了這些接口:dom
ArrayList還間接實現了Iterable和Collection接口。函數
ArrayList 中聲明瞭下面這些屬性:ui
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
// 序列化ID
private static final long serialVersionUID = 8683452581122892189L;
// ArrayList的默認初始容量
private static final int DEFAULT_CAPACITY = 10;
// 一個空的對象數組,用來初始化內容爲空的ArrayList實例
private static final Object[] EMPTY_ELEMENTDATA = {};
// 數據對象數組,真正的數據都保存在這個數組之中,標了transient關鍵字說明該對象數組不參與序列化
transient Object[] elementData;
// 當前ArrayList中包含的元素的個數
private int size;
// 當前ArrayList被修改過的次數
protected transient int modCount = 0;
// ...
}
複製代碼
ArrayList分別提供了下面三個構造函數,首先來看下咱們最常使用的無參構造函數:this
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
複製代碼
很簡單,調用了下父類的構造函數(點進去發現父類構造函數是個空實現),而後將以前聲明的空對象數組EMPTY_ELEMENTDATA賦值給elementData屬性。spa
接着看下能夠傳初始容量的構造函數:code
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
複製代碼
也是先調用父類構造函數,而後判斷若是傳進來的初始化容量initialCapacity小於0則拋出異常,不然建立一個大小爲initialCapacity的對象數組並賦值給elementData。
最後還有個能夠傳集合的構造函數:
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
複製代碼
該方法要求傳入實現了Collection接口的類的對象,而後調用Collection類中的toArray()方法便可將該集合對象中包含的所有元素轉換爲對象數組。 接着再初始化size。
按道理來講這就應該初始化完畢了吧,但是爲何後面又緊跟了一句:
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
複製代碼
原來Collection類的toArray()返回的不必定是Object[]類,舉個例子:
public static void main(String[] args) {
Collection c = Arrays.asList("a", "b", "c");
System.out.println(c.toArray().getClass());
List<Object> list = new ArrayList<>(c);
list.set(0,new Object());
}
複製代碼
運行會發現,打印輸出的是class [Ljava.lang.String;
,所以此時ArrayList內部的elementData即爲String類型了,這時候調用最後一句list.set(0,new Object())則會拋出ArrayStoreException異常,由於你不能往一個String數組設置對象。
先看下最經常使用的add(E e)方法:
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
複製代碼
該方法先調用了ensureCapacityInternal()方法,從方法名能夠猜想,這個方法應該就是用來對數組進行動態擴容的,跳轉到該方法:
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
複製代碼
該方法的參數minCapacity表示當前要求的最小容量,咱們前面傳過來的是size + 1,即最小容量只要比當前元素數量多1就夠了。
若是elementData == EMPTY_ELEMENTDATA,則說明該ArrayList是經過無參構造函數構造的,這時候咱們的minCapacity取默認容量(10)的和傳進來最小容量中較大的那一個。
接着又將minCapacity傳給ensureExplicitCapacity()方法:
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
複製代碼
先自增了一下modCount,而後接着的代碼就好玩了,爲何不直接
if (minCapacity > elementData.length){
grow(minCapacity);
}
複製代碼
而要作個減法跟0比較呢?而後他這兒還有個註釋,說overflow-conscious code又是怎麼回事呢?
好接着點進grow()方法:
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
複製代碼
看到這裏,我不由產生了關掉IDE的衝動。
好的,分狀況討論一下。
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
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;
}
複製代碼
如今咱們假設minCapacity = 16,對象數組elementData的大小仍是10,那麼跟剛剛惟一的區別就是newCapacity - minCapacity = -1 < 0,第一個條件經過,即newCapacity = 16,剩下仍是同樣。
接下來就好玩了,若是當前elementData的大小已經超級大了,我是說超級超級大,大到了接近Integer.MAX_VALUE。
咱們如今假設elementData的大小爲Integer.MAX_VALUE - 100(即2147483547),則minCapacity = Integer.MAX_VALUE - 99(即2147483548),那麼此時再計算newCapacity則會溢出,此時newCapacity = -1073741976,變成了負數;此時newCapacity - minCapacity = 1073741772 > 0,不知足第一個條件;newCapacity - MAX_ARRAY_SIZE = 1073741681 > 0, 經過第二個條件,調用hugeCapacity方法:
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
複製代碼
hugeCapacity方法先判斷minCapacity是否是溢出了,若是溢出了就拋出OutOfMemoryError,接着若是minCapacity沒有溢出可是比MAX_ARRAY_SIZE大,則返回Integer.MAX_VALUE,不然就返回MAX_ARRAY_SIZE。 在咱們舉例的這個狀況下,hugeCapacity方法返回MAX_ARRAY_SIZE,所以最終的newCapacity就等於MAX_ARRAY_SIZE。
接下來考慮一下,若是咱們把grow方法改寫成下面這樣會發生什麼:
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity < minCapacity)
newCapacity = minCapacity;
if (newCapacity > MAX_ARRAY_SIZE)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
複製代碼
仍是套用咱們剛纔的數據,oldCapacity = Integer.MAX_VALUE - 100(2147483547),minCapacity = Integer.MAX_VALUE - 99(即2147483548),newCapacity = -1073741976。會發現,修改過得代碼跟原代碼的運做恰好相反,第一個條件經過,第二個條件則不經過,即不會調用hugeCapacity方法。這樣的話ArrayList就沒法正確地擴容。
到這裏擴容部分的代碼就結束了,回來看一下咱們開始的add方法:
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
複製代碼
正確擴容後,直接將元素e賦值給對象數組elementData下標爲size的位置,由於此時size就是添加的元素應該在的下標,而後將size自增。
接下來看下add(int index, E element)方法,在特定的下標index處插入元素:
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,size - index);
elementData[index] = element;
size++;
}
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
複製代碼
首先調用了rangeCheckForAdd方法檢查下標index是否合法,不合法拋出異常IndexOutOfBoundsException。
而後是調用ensureCapacityInternal方法進行擴容,確保ArrayList容量夠存放size + 1個元素。
接下來的System.arraycopy(elementData, index, elementData, index + 1,size - index)
作的是將從index開始的元素所有都日後移動一位,若是原來的元素是[1,2,4,5],index = 2,element = 3,通過這步會變成[1,2,4,4,5]。
接着就把元素element覆蓋到數組中index的位置。即變成了[1,2,3,4,5]。
最後將size自增。
該方法最壞的狀況是index = 0,由於這樣的話當前ArrayList中所有的元素都得日後移動一位。
咱們剛看完了添加單個元素,如今來看下如何添加多個元素,ArrayList提供了addAll(Collection<? extends E> c)方法:
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
複製代碼
該方法的參數也是Collection接口,調用Collection提供的toArray方法將Collection中的所有元素轉換爲對象數組a;接着獲取該數組的大小並賦值給numNew,而後一樣是調用ensureCapacityInternal進行擴容。確保ArrayList容量能夠存放size + numNew個元素後,直接將對象數組a中的所有元素從末尾拷貝進elementData。最後正確增長size,若是numNew不爲0返回true,不然返回false。
這裏我不理解的是,爲何不先判斷集合是否爲空,若是爲空直接返回false就省去了後面的方法調用,有知道的朋友麻煩告訴我噢!
ArrayList還提供了addAll(int index, Collection<? extends E> c)方法,能夠從指定位置index開始插入多個元素:
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew);
int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
複製代碼
一樣先經過調用rangeCheckForAdd方法判斷index是否合法,index合法後接下來仍是先調Collection的toArray方法轉換爲對象數組a,而後同樣調用ensureCapacityInternal方法。
跟前面的addAll方法不一樣的是,咱們這裏可能要移動一些元素,所以經過size - index先計算要移動的元素個數,若是numMoved大於0則說明須要移動元素,即將index開始的元素通通日後numNew位;不然numMoved等於0,說明直接從末尾添加,無需移動元素。
接下來將對象數組a中的所有元素從index開始拷貝到elementData中。最後正確增長size。若是numNew不等於0返回true。
訪問數據比較簡單,ArrayList提供了get()方法:
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
E elementData(int index) {
return (E) elementData[index];
}
複製代碼
首先調用rangeCheck(int index)方法檢查下標是否超出了範圍,而後經過調用封裝好的elementData(int index)方法獲取index對應的元素。
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
複製代碼
indexOf分兩種狀況,若是查找的對象爲null,則經過for循環找到第一個爲null的元素的位置並返回了;若是查找的對象不爲null,則經過調用equals()方法判斷是否同一個元素,找到即返回位置;若是沒找到返回-1。
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
複製代碼
lastIndexOf()方法跟indexOf()方法惟一的區別就是它的for循環是從後往前的。
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
複製代碼
contains方法是經過調用indexOf方法實現的,若是indexOf方法返回的數字大於等於零,說明對象o存在,不然返回-1。
remove(int index)方法用來刪除指定下標的元素:
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
複製代碼
remove方法的操做是,把index後面的元素都往前移一位,而後刪除最後一個元素。
remove(Object o) 能夠用來刪除某指定元素
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;
}
複製代碼
該方法跟indexOf(Object o)很是類似。remove(Object o)方法找到元素所在位置後,調用fastRemove(int index)方法刪除元素:
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; // clear to let GC do its work
}
複製代碼
fastRemove(int index)跟remove(int index)方法的區別是,它不檢查index,也不返回刪除的元素。
ArrayList提供了set(int index, E element)方法來更新某位置的值,也比較簡單:
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
複製代碼
先調用rangeCheck()方法保證index合法,接下來調用elementData()方法獲取index位置的元素並保存在局部變量oldValue中,而後將該位置的元素更新爲element,最後返回oldValue。
trimToSize()方法能夠用來將對象數組的大小壓縮到跟size同樣大:
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = Arrays.copyOf(elementData, size);
}
}
複製代碼
size()方法返回當前包含的元素大小
public int size() {
return size;
}
複製代碼
判斷當前ArrayList內的元素是否爲空
public boolean isEmpty() {
return size == 0;
}
複製代碼
返回包含當前ArrayList所有元素的對象數組
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
複製代碼
清除當前ArrayList中所有元素
public void clear() {
modCount++;
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
複製代碼
就把對象數組中每一個元素設爲null,而後size重置爲0。
根據傳進來的Comparator對ArrayList中的元素進行排序:
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
複製代碼
具體的排序經過調用Arrays中的靜態方法sort(T[] a, int fromIndex, int toIndex,Comparator<? super T> c)。