集合系列文章:和我一起讀Java8 LinkedList源碼
首先放一張Java集合接口圖:
Collection是一個(gè)獨(dú)立元素序列,這些元素都服從一條或多條規(guī)則,List必須按照插入的順序保存元素,而Set不能有重復(fù)元素,Queue按照排隊(duì)規(guī)則來確定對(duì)象產(chǎn)生的順序。
List在Collection的基礎(chǔ)上添加了大量的方法,使得可以在List的中間插入和移除元素。
有2種類型的List:
- ArrayList 它長于隨機(jī)訪問元素,但是在List中間插入和移除元素較慢。
-
LinkedList 它通過代價(jià)較低的方式在List中間進(jìn)行插入和刪除,但是在隨機(jī)訪問方面相對(duì)較慢,但是它的特性急較ArrayList大。
還有個(gè)第一代容器Vector,后面僅作比較。
下面正式進(jìn)入ArrayList實(shí)現(xiàn)原理,主要參考Java8 ArrayList源碼
類定義
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
ArrayList 繼承了AbstractList并且實(shí)現(xiàn)了List,所以具有添加,修改,刪除,遍歷等功能
實(shí)現(xiàn)了RandomAccess接口,支持隨機(jī)訪問
實(shí)現(xiàn)了Cloneable接口,支持Clone
實(shí)現(xiàn)了Serualizable接口,可以被序列化
底層數(shù)據(jù)結(jié)構(gòu)
transient Object[] elementData; //存放元素的數(shù)組
private int size; //ArrayList實(shí)際存放的元素?cái)?shù)量
ArrayList的底層實(shí)際是通過一個(gè)Object的數(shù)組實(shí)現(xiàn),數(shù)組本身有個(gè)容量capacity,實(shí)際存儲(chǔ)的元素個(gè)數(shù)為size,當(dāng)做一些操作,例如插入操作導(dǎo)致數(shù)組容量不夠時(shí),ArrayList就會(huì)自動(dòng)擴(kuò)容,也就是調(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);
}
}
初始化一個(gè)指定容量的空集合,若是容量為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ù)初始化,其實(shí)DEFAULTCAPACITY_EMPTY_ELEMENTDATA
的定義也為:
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
與EMPTY_ELEMENTDATA
的區(qū)別是當(dāng)?shù)谝粋€(gè)元素被插入時(shí),數(shù)組就會(huì)自動(dòng)擴(kuò)容到10,具體見下文說add方法時(shí)的解釋。
集合作為初始化參數(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)造一個(gè)包含指定 collection 的元素的列表,這些元素按照該collection的迭代器返回它們的順序排列的。
size和IsEmpty
首先是兩個(gè)最簡(jiǎn)單的操作:
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
都是依靠size值,直接獲取容器內(nèi)元素的個(gè)數(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);
}
在操作之前都會(huì)做RangeCheck檢查,如果index超過size,則會(huì)報(bào)IndexOutOfBoundsException錯(cuò)誤。
elementData的操作實(shí)際就是基于下標(biāo)的訪問,所以ArrayList 長于隨機(jī)訪問元素,復(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的實(shí)現(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值的,如果不存在該元素,則會(huì)返回-1
,所以contains判斷是否大于等于0來判斷是否包含指定元素。
Add和Remove
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
首先確保已有的容量在已使用長度加1后還能存下下一個(gè)元素,這里正好分析下用來確保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添加第一個(gè)元素,上面的if語句就會(huì)調(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ù), 然后是判斷是否需要擴(kuò)充數(shù)組容量,如果當(dāng)前數(shù)組所需要的最小容量大于數(shù)組現(xiàn)有長度,就調(diào)用自動(dòng)擴(kuò)容函數(shù)grow:
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); //擴(kuò)充為原來的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直接將長度擴(kuò)展為原來的1.5倍,如果1.5倍的長度大于需要擴(kuò)充的容量(minCapacity),就只擴(kuò)充到minCapacity,如果newCapacity大于數(shù)組最大長度MAX_ARRAY_SIZE,就只擴(kuò)容到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還提供兩個(gè)參數(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接口也很好理解了,存儲(chǔ)index位置的值到oldView作為返回值,將index后面所有的元素都向前拷貝一位,不要忘記的是還要將原來最后的位置標(biāo)記為null,以便讓垃圾收集器自動(dòng)GC這塊內(nèi)存。
還可以根據(jù)對(duì)象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;
}
找到對(duì)象所在位置,調(diào)用FastRemove函數(shù)快速刪除index位置上的元素,F(xiàn)astRemove也就是比remove(index)少了個(gè)邊界檢查。
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機(jī)制,所以不需要手動(dòng)釋放內(nèi)存,只要將ArrayList所有元素都標(biāo)記為null,垃圾收集器就會(huì)自動(dòng)收集這些內(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) ;
相比于單文件一次只集體向前或向后移動(dòng)一位,批量操作需要移動(dòng)Collection 長度的距離。
Iterator與fast_fail
首先看看ArrayList里迭代器是如何實(shí)現(xiàn)的:
private class Itr implements Iterator<E> {
int cursor; // 記錄下一個(gè)返回元素的index,一開始為0
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount; //這邊確保產(chǎn)生迭代器時(shí),就將當(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在這里會(huì)記錄最近返回元素的位置
}
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ù)會(huì)改變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一個(gè)上述迭代器對(duì)象:
public Iterator<E> iterator() {
return new Itr();
}
那么我們看看Itr
類的主要方法:
- next :獲取序列的下一個(gè)元素
- hasNext:檢查序列中是否還有元素
- remove:將迭代器新近返回的元素刪除
在next和remove操作之前,都會(huì)調(diào)用checkForComodification函數(shù),如果modCount和本身記錄的expectedModCount不一致,就證明集合在別處被修改過,拋出ConcurrentModificationException異常,產(chǎn)生fail-fast事件。
fail-fast 機(jī)制是java集合(Collection)中的一種錯(cuò)誤機(jī)制。當(dāng)多個(gè)線程對(duì)同一個(gè)集合的內(nèi)容進(jìn)行操作時(shí),就可能會(huì)產(chǎn)生fail-fast事件。
例如:當(dāng)某一個(gè)線程A通過iterator去遍歷某集合的過程中,若該集合的內(nèi)容被其他線程所改變了;那么線程A訪問集合時(shí),就會(huì)拋出ConcurrentModificationException異常,產(chǎn)生fail-fast事件。
一般多線程環(huán)境下,可以考慮使用CopyOnWriteArrayList來避免fail-fast。