集合系列文章:和我一起讀Java8 LinkedList源碼
首先放一張Java集合接口圖:
Collection是一個獨立元素序列钢猛,這些元素都服從一條或多條規(guī)則伙菜,List必須按照插入的順序保存元素,而Set不能有重復(fù)元素厢洞,Queue按照排隊規(guī)則來確定對象產(chǎn)生的順序仇让。
List在Collection的基礎(chǔ)上添加了大量的方法典奉,使得可以在List的中間插入和移除元素。
有2種類型的List:
- ArrayList 它長于隨機訪問元素丧叽,但是在List中間插入和移除元素較慢卫玖。
-
LinkedList 它通過代價較低的方式在List中間進(jìn)行插入和刪除,但是在隨機訪問方面相對較慢踊淳,但是它的特性急較ArrayList大假瞬。
還有個第一代容器Vector,后面僅作比較迂尝。
下面正式進(jìn)入ArrayList實現(xiàn)原理脱茉,主要參考Java8 ArrayList源碼
類定義
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
ArrayList 繼承了AbstractList并且實現(xiàn)了List,所以具有添加垄开,修改琴许,刪除,遍歷等功能
實現(xiàn)了RandomAccess接口溉躲,支持隨機訪問
實現(xiàn)了Cloneable接口榜田,支持Clone
實現(xiàn)了Serualizable接口,可以被序列化
底層數(shù)據(jù)結(jié)構(gòu)
transient Object[] elementData; //存放元素的數(shù)組
private int size; //ArrayList實際存放的元素數(shù)量
ArrayList的底層實際是通過一個Object的數(shù)組實現(xiàn)锻梳,數(shù)組本身有個容量capacity箭券,實際存儲的元素個數(shù)為size,當(dāng)做一些操作疑枯,例如插入操作導(dǎo)致數(shù)組容量不夠時辩块,ArrayList就會自動擴容,也就是調(diào)節(jié)capacity的大小荆永。
初始化
指定容量大小初始化
/**
* 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,集合為空集合屁魏,其中
private static final Object[] EMPTY_ELEMENTDATA = {};
,容量也為0滔以。
無參數(shù)初始化
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
無參數(shù)初始化,其實DEFAULTCAPACITY_EMPTY_ELEMENTDATA
的定義也為:
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
與EMPTY_ELEMENTDATA
的區(qū)別是當(dāng)?shù)谝粋€元素被插入時,數(shù)組就會自動擴容到10,具體見下文說add方法時的解釋抵碟。
集合作為初始化參數(shù)
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
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;
}
}
構(gòu)造一個包含指定 collection 的元素的列表敦迄,這些元素按照該collection的迭代器返回它們的順序排列的苦囱。
size和IsEmpty
首先是兩個最簡單的操作:
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
都是依靠size值,直接獲取容器內(nèi)元素的個數(shù)蚀狰,判斷是否為空集合。
Set 和Get操作
Set和Get操作都是直接操作集合下標(biāo)
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);
}
在操作之前都會做RangeCheck檢查,如果index超過size,則會報IndexOutOfBoundsException錯誤。
elementData的操作實際就是基于下標(biāo)的訪問,所以ArrayList 長于隨機訪問元素掌呜,復(fù)雜度為O(1)翩肌。
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
Contain
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
contains 函數(shù)基于indexOf函數(shù),如果第一次出現(xiàn)的位置大于等于0瓷产,說明ArrayList就包含該元素, IndexOf的實現(xiàn)如下:
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;
}
ArrayList是接受null值的,如果不存在該元素铃拇,則會返回-1
缠俺,所以contains判斷是否大于等于0來判斷是否包含指定元素磷雇。
Add和Remove
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
首先確保已有的容量在已使用長度加1后還能存下下一個元素,這里正好分析下用來確保ArrayList容量ensureCapacityInternal
函數(shù):
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
這邊可以返回看一開始空參數(shù)初始化少办,this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA
, 空參數(shù)初始化的ArrayList添加第一個元素挽放,上面的if語句就會調(diào)用贺纲,DEFAULT_CAPACITY
定義為10懈叹,所以空參數(shù)初始化的ArrayList一開始添加元素澄成,容量就變?yōu)?0胧洒,在確定了minCapacity后,還要調(diào)用ensureExplicitCapacity(minCapacity)
去真正的增長容量:
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
這里modCount默默記錄ArrayList被修改的次數(shù)墨状, 然后是判斷是否需要擴充數(shù)組容量卫漫,如果當(dāng)前數(shù)組所需要的最小容量大于數(shù)組現(xiàn)有長度,就調(diào)用自動擴容函數(shù)grow:
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); //擴充為原來的1.5倍
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);
}
oldCapacity記錄數(shù)組原有長度肾砂,newCapacity直接將長度擴展為原來的1.5倍列赎,如果1.5倍的長度大于需要擴充的容量(minCapacity),就只擴充到minCapacity镐确,如果newCapacity大于數(shù)組最大長度MAX_ARRAY_SIZE包吝,就只擴容到MAX_ARRAY_SIZE大小,關(guān)于MAX_ARRAY_SIZE為什么是private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
,我文章里就不深究了源葫,感興趣的可以參考stackoverflow上的有關(guān)回答:
Why the maximum array size of ArrayList is Integer.MAX_VALUE - 8?
Add還提供兩個參數(shù)的形式诗越,支持在指定位置添加元素。
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++;
}
在指定位置添加元素之前息堂,先把index位置起的所有元素后移一位嚷狞,然后在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位置的值到oldView作為返回值感耙,將index后面所有的元素都向前拷貝一位,不要忘記的是還要將原來最后的位置標(biāo)記為null持隧,以便讓垃圾收集器自動GC這塊內(nèi)存即硼。
還可以根據(jù)對象Remove:
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;
}
找到對象所在位置,調(diào)用FastRemove函數(shù)快速刪除index位置上的元素屡拨,F(xiàn)astRemove也就是比remove(index)少了個邊界檢查只酥。
clear
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
由于Java有GC機制,所以不需要手動釋放內(nèi)存呀狼,只要將ArrayList所有元素都標(biāo)記為null裂允,垃圾收集器就會自動收集這些內(nèi)存。
Add和Remove都提供了一系列的批量操作接口:
public boolean addAll(Collection<? extends E> c);
public boolean addAll(int index, Collection<? extends E> c);
protected void removeRange(int fromIndex, int toIndex) ;
public boolean removeAll(Collection<?> c) ;
相比于單文件一次只集體向前或向后移動一位哥艇,批量操作需要移動Collection 長度的距離绝编。
Iterator與fast_fail
首先看看ArrayList里迭代器是如何實現(xiàn)的:
private class Itr implements Iterator<E> {
int cursor; // 記錄下一個返回元素的index,一開始為0
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount; //這邊確保產(chǎn)生迭代器時,就將當(dāng)前modCount賦給expectedModCount
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor; //訪問元素的index
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1; //不斷加1十饥,只要不斷調(diào)用next窟勃,就可以遍歷List
return (E) elementData[lastRet = i]; //lastRet在這里會記錄最近返回元素的位置
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet); //調(diào)用List本身的remove函數(shù),刪除最近返回的元素
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount; //上面的Remove函數(shù)會改變modCount逗堵,所以這邊expectedModCount需要更新
} 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() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
ArrayList里可以通過iterator方法獲取迭代器秉氧,iterator方法就是new一個上述迭代器對象:
public Iterator<E> iterator() {
return new Itr();
}
那么我們看看Itr
類的主要方法:
- next :獲取序列的下一個元素
- hasNext:檢查序列中是否還有元素
- remove:將迭代器新近返回的元素刪除
在next和remove操作之前,都會調(diào)用checkForComodification函數(shù)蜒秤,如果modCount和本身記錄的expectedModCount不一致汁咏,就證明集合在別處被修改過,拋出ConcurrentModificationException異常作媚,產(chǎn)生fail-fast事件攘滩。
fail-fast 機制是java集合(Collection)中的一種錯誤機制。當(dāng)多個線程對同一個集合的內(nèi)容進(jìn)行操作時掂骏,就可能會產(chǎn)生fail-fast事件轰驳。
例如:當(dāng)某一個線程A通過iterator去遍歷某集合的過程中,若該集合的內(nèi)容被其他線程所改變了弟灼;那么線程A訪問集合時级解,就會拋出ConcurrentModificationException異常,產(chǎn)生fail-fast事件田绑。
一般多線程環(huán)境下勤哗,可以考慮使用CopyOnWriteArrayList來避免fail-fast。