ArrayList 源碼分析
1. 數(shù)組介紹
數(shù)組是數(shù)據(jù)結(jié)構(gòu)中很基本的結(jié)構(gòu),很多編程語言都內(nèi)置數(shù)組。
在 Java 中當(dāng)創(chuàng)建數(shù)組時(shí)會(huì)在內(nèi)存中劃分一塊連續(xù)的內(nèi)存,然后當(dāng)有數(shù)據(jù)進(jìn)入的時(shí)候會(huì)將數(shù)據(jù)按順序的存儲(chǔ)在這塊連續(xù)的內(nèi)存中。當(dāng)需要讀取數(shù)組中的數(shù)據(jù)時(shí),需要提供數(shù)組中的索引,然后數(shù)組根據(jù)索引將內(nèi)存中的數(shù)據(jù)取出來,返回給讀取程序。在 Java 中并不是所有的數(shù)據(jù)都能存儲(chǔ)到數(shù)組中,只有相同類型的數(shù)據(jù)才可以一起存儲(chǔ)到數(shù)組中。
注意:
因?yàn)閿?shù)組在存儲(chǔ)數(shù)據(jù)時(shí)是按順序存儲(chǔ)的,存儲(chǔ)數(shù)據(jù)的內(nèi)存也是連續(xù)的,所以它的特點(diǎn)就是尋址讀取數(shù)據(jù)比較容易(直接通過下標(biāo)讀?。迦牒蛣h除比較困難(需要移動(dòng)元素)。
2. ArrayList 源碼分析
alt + 7:查看一個(gè)類中的所有方法
構(gòu)造方法
// 指定長度
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
// 創(chuàng)建指定長度的 Object 數(shù)組
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
// 空數(shù)組
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
// 空參構(gòu)造方法
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
// 傳遞集合對(duì)象方法
public ArrayList(Collection<? extends E> c) {
// 轉(zhuǎn)換為數(shù)組
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
// 這是一個(gè) bug,c.toArray 有可能返回的不是 Object[] 類型,此問題在 JDK9 已經(jīng)被修復(fù)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// 數(shù)組長度為0,返回空數(shù)組
this.elementData = EMPTY_ELEMENTDATA;
}
}
插入數(shù)據(jù)
// 插入元素
public boolean add(E e) {
// 檢測是否擴(kuò)容
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
// 指定位置插入元素
public void add(int index, E element) {
// 判斷 index 是否越界
rangeCheckForAdd(index);
// 檢測是否需要擴(kuò)容
ensureCapacityInternal(size + 1);
// 將 index 之后的所有元素向后移動(dòng)一位
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
// 將 index 位置覆蓋新值
elementData[index] = element;
// 長度加 1
size++;
}
擴(kuò)容操作
// 擴(kuò)容的入口方法
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// 計(jì)算最小容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
// 默認(rèn)容量 10
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 超過過數(shù)組長度則進(jìn)行擴(kuò)容,若沒有初始化容量大小,則默認(rèn)為10
// 是否滿足擴(kuò)容的條件 最小容量 - object 數(shù)組的長度
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
// 數(shù)組擴(kuò)容方法
private void grow(int minCapacity) {
// 當(dāng)前數(shù)組長度
int oldCapacity = elementData.length;
// 新的數(shù)組容量 = 老容量 + 老容量 / 2(1.5倍)【右移一位即 / 2】
// eg: oldCapacity = 10
// oldCapacity >> 1
// 0000 1010 >> 1
// 0000 0101 = 5
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
刪除方法
// 指定下標(biāo)刪除
public E remove(int index) {
// 檢測 index 值是否越界,IndexOutOfBoundsException
rangeCheck(index);
modCount++;
// 返回要?jiǎng)h除的元素
E oldValue = elementData(index);
// 將 index+1 及之后的元素向前移動(dòng)一位,覆蓋被刪除的值
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// 將最后一個(gè)位置的元素清空
elementData[--size] = null;
return oldValue;
}
// 指定元素刪除
public boolean remove(Object o) {
// 判斷元素是否為 null
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;
}
}
// 如果沒有匹配,返回 false
return false;
}
// 快速刪除,沒有檢測 index 下標(biāo)
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;
}
遍歷
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(11);
list.add(12);
list.add(13);
list.add(15);
// for-each 刪除
for (Integer num : list) {
if (num == 12) {
list.remove(num);
}
}
// 報(bào)錯(cuò)
// Exception in thread "main" java.util.ConcurrentModificationException
// 因?yàn)?ArrayList 源碼中
final void checkForComodification() {
// modCount 值和 expectedModCount 值不相等就異常
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
// 解決異常問題
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
Integer num = it.next();
if (num == 12) {
// 使用迭代器的刪除方法
it.remove();
}
}
- for-each 方法
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();
}
- iterator 方法中
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
// 修改 expectedModCount 值和當(dāng)前 modCount 一樣
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
可以看到 Iterator 方法的 remove() 方法中將 expectedModCount 值修改成和當(dāng)前 modCount 一樣,便不會(huì)拋出 ConcurrentModificationException 異常。
總結(jié):我們應(yīng)該使用 迭代器 Iterator 來刪除元素而不應(yīng)該使用 for-each 方法。