前言
ArrayList可以說是我們?nèi)粘i_發(fā)中特別經(jīng)常使用到的集合類了,本文將結(jié)合JDK1.8源碼從線程安全、數(shù)據(jù)結(jié)構(gòu)、初始化、擴(kuò)容、增刪改查、特性總結(jié)等幾個部分去分析ArrayList
線程安全
ArrayList是非線程安全的,不支持并發(fā)。我們可以從它的數(shù)據(jù)迭代器ArrayList$Itr中可以得知,當(dāng)產(chǎn)生線程安全問題時會拋出拋出ConcurrentModificationException異常。內(nèi)部是通過一個modCount變量記錄集合的變化,在擴(kuò)容與刪除及清空等操作都會將modCount自增,以此來標(biāo)記集合的改變。
如何實現(xiàn)線程安全
1.通過Colletions.synchronizedCollection獲取線程安全的集合對象
2.使用并發(fā)庫下的CopyOnWriteArrayList(讀寫分離)
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
int expectedModCount = modCount; // 記錄初始modCount
......
@SuppressWarnings("unchecked")
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];
}
// 在next與remove前都會檢查modCount是否改變
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
數(shù)據(jù)結(jié)構(gòu)
ArrayList采用數(shù)組對數(shù)據(jù)進(jìn)行管理,大量采用了數(shù)組的copy實現(xiàn)增刪。因此對于性能上,ArrayList的增刪操作較慢,由于數(shù)組是連續(xù)的內(nèi)存空間所以改查較快。
初始化
提供了三個重載構(gòu)造方法,除了默認(rèn)的無參構(gòu)造器外還可以指定初始容量以及初始集合內(nèi)容。需要注意的是在參數(shù)無效時(初始容量指定為0或者集合)都跟默認(rèn)構(gòu)造器結(jié)果一致,將數(shù)據(jù)指定為默認(rèn)的空數(shù)組,這樣的好處是當(dāng)該list沒有真正去使用時不會浪費(fèi)內(nèi)存。
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) { // 構(gòu)造數(shù)據(jù)
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) { // 指定為空數(shù)組
this.elementData = EMPTY_ELEMENTDATA;
} else { // 拋出異常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
public ArrayList() { // 空構(gòu)造器直接指定數(shù)組為空數(shù)組
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray(); // 將集合轉(zhuǎn)為數(shù)組
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
// 通過Arrays.copyOf方法進(jìn)行數(shù)組復(fù)制,得到新數(shù)組。底層是通過System.arraycopy進(jìn)行的,本質(zhì)是native
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
擴(kuò)容
ArrayList的擴(kuò)容其實就是數(shù)組的擴(kuò)容,而實際上數(shù)組是沒辦法擴(kuò)容的。所以只能夠構(gòu)造新的數(shù)組,然后把原數(shù)組的數(shù)據(jù)進(jìn)行copy到新數(shù)組,以此完成擴(kuò)容操作。默認(rèn)為原數(shù)組的1.5倍
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++; // modCount之前提到了,用于并發(fā)異??刂? // overflow-conscious code 需要擴(kuò)容(需要的容量>=當(dāng)前容量)
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 默認(rèn)擴(kuò)容為之前的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 如果1.5倍仍然無法滿足,則直接擴(kuò)容為minCapacity
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:
// 數(shù)組復(fù)制完成擴(kuò)容
elementData = Arrays.copyOf(elementData, newCapacity);
}
增操作
增操作首先進(jìn)行一些基本條件判斷,包括是否擴(kuò)容、指定的index是否越界。在add(int index, E element)方法中也需要進(jìn)行擴(kuò)容,因為可能添加新元素后,新size可能剛好等于當(dāng)前容量。賦值就很簡單了,因為是數(shù)組結(jié)構(gòu),直接通過index指定即可,唯一需要注意的是在賦值之前的數(shù)組copy
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
// 將數(shù)組進(jìn)行拷貝,留出index位置
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
// 對index位置進(jìn)行賦值
elementData[index] = element;
size++;
}
刪操作
刪除操作有兩種形式,指定對象或者指定位置,注意此處也修改modCount變量了。指定位置:首先越界檢查,接著通過數(shù)組copy將指定index的位置覆蓋,最后指定--size為null。指定對象:分兩種情況,一種是對象為null,一種是對象非空。
public E remove(int index) {
rangeCheck(index); // 越界檢查
modCount++;
E oldValue = elementData(index); // 刪除的目標(biāo)對象
int numMoved = size - index - 1; // 數(shù)據(jù)需要移動的數(shù)量
if (numMoved > 0) // copy
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// 最后一個賦值null
elementData[--size] = null; // clear to let GC do its work
// 返回目標(biāo)對象
return oldValue;
}
public boolean remove(Object o) {
// 指定對象的remove操作是通過循環(huán)比較
if (o == null) { // null
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true; // 返回的boolean表示是否移除成功
}
} else { // 非空
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
改操作
很簡單,越界檢查 - > 取原值 - > 修改 - > 返回原值
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
查操作
很簡單,越界檢查 - > 返回對象
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
特性總結(jié)
1.數(shù)據(jù)結(jié)構(gòu)為數(shù)據(jù),增刪慢、改查快
2.非線程安全,通過modCount控制
3.ArrayList與Vector的區(qū)別:Vector是線程安全的,通過synchronized關(guān)鍵字;Vector擴(kuò)容是容量翻倍,而ArrayList是原容量1.5倍