本文通過源碼來總結一下ArrayList
ArrayList
ArrayList 底層上是一個動態數組
屬性
// 默認初始容量
private static final int DEFAULT_CAPACITY = 10;
// 指定容量爲0時,數組爲該值
private static final Object[] EMPTY_ELEMENTDATA = {};
// 調用無參構造方法,數組爲該值,初次add元素時擴容爲默認10
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 元素數組,有transient關鍵字,不會被序列化
transient Object[] elementData; // non-private to simplify nested class access
// list的大小,就是elementData數組的長度
private int size;
可以看到這裏有兩個空數組,具體區別下面會提到
構造方法
提供了三個構造方法
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);
}
}
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
1、指定初始化容量
- 大於0則初始化一個指定容量的數組
- 等於0則將EMPTY_ELEMENTDATA空數組作爲elementData
2、無參數構造方法
將DEFAULTCAPACITY_EMPTY_ELEMENTDATA空數組作爲elementData
默認容量大小爲10,但是這時候還沒有初始化
3、Collection參數
通過toArray方法獲取到的數組賦值給elementData,長度爲0則用空數組代替
但是這裏可以看到,如果長度不爲0的話,進行了類型的判斷,將非Object[]類型的複製爲Object[]類型
註釋說明因爲c.toArray可能返回的不是Object[]類型,官網查找該bug描述
Arrays.asList構建出來的List,如果創建的是String類型的,toArray方法返回的就是String[]類型的數組,如果之後在該List中再add其他類型的數據,會拋出ArrayStoreException異常
例如
List list = new ArrayList(Arrays.asList("one", "two", "three"));
所以此處爲了避免這樣的情況,對非Object[]類型做了特殊處理
獲取元素
因爲底層是數組,所以直接通過下標獲取,時間複雜度爲O(1)
public E get(int index) {
// 範圍檢查,數組越界
rangeCheck(index);
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
添加元素
因爲是動態數組,所以添加元素時會涉及到擴容
1、通過calculateCapacity方法計算當前所需容量大小
2、ensureExplicitCapacity方法確定是否執行擴容
3、grow方法執行擴容,進行數組copy
public boolean add(E e) {
// 確認是否需要擴容,所需最小容量傳遞當前容量+1
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) {
// 如果是無參構造方法初始化的數組,返回默認大小10
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
// 否則返回所需最小容量(當前size + 1)
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 現在的數組容量小於所需最小容量,則擴容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
// 進行擴容
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 先擴容爲原來的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 1.5倍後還小於所需最小容量,則直接擴容爲所需最小容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
// 如果大於最大數組容量,則擴容爲Integer最大數值
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 進行數組copy
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
默認容量爲10,但是初始化的時候是個空數組,在第一次add元素的時候會擴容到10
可以看到,擴容需要進行數組copy,所以如果是數據量很大又頻繁add數據的情況下,最好是初始化時能指定容量
更新元素
指定下標,直接替換新值,返回舊的值
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
刪除元素
刪除指定下標元素
public E remove(int index) {
rangeCheck(index);
modCount++;
// 通過下標獲取到待刪除元素
E oldValue = elementData(index);
// 計算需要移動的元素數量,被刪元素後面的都需要移動
int numMoved = size - index - 1;
if (numMoved > 0)
// 數組copy移動
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
刪除某個元素
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;
}
找到被刪除元素的下標,刪除操作同指定下標的刪除方法(數組copy),批量刪除的方法也是如此
迭代
ArrayList繼承自AbstractList,有個很重要的屬性modCount,它表示數據結構被修改的次數
可以看到,只要是數據結構發生變化的時候,都會對應的變更modCount的值,如新增,刪除,清除等方法
作用就是爲了防止在迭代遍歷的時候,其他線程對數據結構進行了修改
如果子類需要提供迭代時快速失敗機制,就需要在數據結構性變化的方法記錄modCount
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
// 記錄modCount
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
// 每次遍歷前檢查modCount
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];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
// 遍歷刪除元素前,判斷modCount
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
// 更新modCount記錄
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
// modCount有變更,說明有其他線程對數組結構進行了修改,拋出異常
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
總結
- ArrayList底層爲動態數組
- 默認容量爲10,在第一次添加元素時候會擴容到10
- 每次擴容會變爲之前的1.5倍,會涉及到數組的拷貝
- 獲取元素通過下標直接獲取,速度快
- 在尾部進行元素的添加和刪除效率較高,在中間添加和刪除效率低,因爲涉及到元素的移動
- 在大數據量的前提下,最好預估容量,初始化時候指定,避免擴容時進行的數組copy影響效率