一、ArrayList源碼分析(JDK7)
ArrayList內部維護了一個動態Object數組,ArrayList的動態增刪就是對這個對組的動態增加和刪除。
1、ArrayList構造以及初始化
ArrayList執行個體變數//ArrayList預設容量private static final int DEFAULT_CAPACITY = 10;//預設空的Object數組, 用於定義空的ArrayListprivate static final Object[] EMPTY_ELEMENTDATA = {};//ArrayList存放存放元素的Object數組private transient Object[] elementData;//ArrayList中元素的數量private int size;
ArrayList建構函式:
無參建構函式: 即構造一個空的Object[]
public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA;}
指定容量大小構造:
public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity];}
指定某一實現Collection介面的集合構造:
public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class);}
這裡也說明了Collection的作用, java-collection-framwork設計Collection介面而不是直接使用List,Set等介面的原因。
2、ArrayList的容量分配機制
ArrayList的容量上限: ArrayList容量是有上限的,理論允許分配Integer.Max_VALUE - 8大小的容量。但是能分配多少還跟堆棧設定有關, 需要設定VM參數
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
調用Add方法時擴容規則
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
ensureCapacityInternal(int)方法實際上確定一個最小擴容大小。
private void ensureCapacityInternal(int minCapacity) { if (elementData == EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); }private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }
關於modCount: modCount定義在抽象類別AbstratList中, 源碼的注釋基本說明了它的用處:在使用迭代器遍曆的時候,用來檢查列表中的元素是否發生結構性變化(列表元素數量發生改變的一個計數)了,主要在多線程環境下需要使用,防止一個線程正在迭代遍曆,另一個線程修改了這個列表的結構。
grow方法為真正的擴容方法
private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; 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); }
其中對大容量擴容多少還有個hugeCapacity方法
private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }
總結:
每次擴容都會伴隨著數組的複製操作, 因此一次給定恰當的容量會提高一點效能。
下圖是我歸納的整個擴容流程:
3.ArrayList迭代器
ArrayList的迭代器主要有兩種Itr和ListItr, 但是在jDK1.8中還添加了一個ArrayListSpliterator, 下面分別學一下Itr和ListItr的源碼分析。
(1)Itr:只能向後遍曆
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 //expectedModCount 是modCount的一個副本 int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @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]; } //使用迭代器的remove方法 public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { //注意內部類調用外部類的方式 ArrayList.this.remove(lastRet); //remove之後需要重新調整各個指標的位置 cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
從源碼中可以看出Itr迭代器是向前迭代器, 它提供了一個next方法用於擷取ArrayList中的元素。
checkForComodification是java-collection-framwork中的一種fail-fast的錯誤偵測機制。在多線程環境下對同一個集合操作,就可能觸發fail-fast機制, 拋出ConcurrentModificationException異常。
Itr迭代器定義了一個expectedModCount記錄modCount副本。在ArrayList執行改變結構的操作的時候例如Add, remove, clear方法時modCount的值會改變。
通過Itr源碼可以看出調用next和remove方法會觸發fail-fast檢查。此時如果在遍曆該集合時, 存在其他線程正在執行改變該集合結構的操作時就會發生異常。
(2)ListItr:支援向前和向後遍曆,下面看看ListItr的源碼:
private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } @SuppressWarnings("unchecked") public E previous() { checkForComodification(); //arrayList前一個元素的位置 int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; } //該迭代器中添加了set方法 public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } //該迭代器添加了add方法 public void add(E e) { checkForComodification(); try { int i = cursor; ArrayList.this.add(i, e); //重新標記指標位置 cursor = i + 1; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } }
ListItr的實現基本與Itr一致, 添加了可以先前遍曆的方法以及add與set方法。
(3)使用java.util.concurrent中的CopyOnWriteArrayList解決fast-fail問題
CopyOnWriteArrayList是安全執行緒的, 具體看一下它的add方法源碼:
public boolean add(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } }
CopyOnWriteArrayList就是寫時複製的ArrayList。當開始寫資料的操作時候, Arrays.copyOf一個新的數組, 這樣不會影響讀操作。
這樣的代價就是會損耗記憶體, 帶來效能的問題。CopyOnWriteArrayList寫的時候在記憶體中產生一個副本對象, 同時原來的對象仍然存在。
CopyOnWriteArrayList無法保證資料即時的一致, 只能保證結果的一致。適用於並發下讀多寫少得情境, 例如緩衝。
(4)ArrayList的其他方法源碼:
一個私人方法batchRemove(Collection<?>c, boolean complement), 即大量移除操作
private boolean batchRemove(Collection<?> c, boolean complement) { //下面會提到使用final的原因 final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { //遍曆List中的元素,進行驗證 for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { //try中如果出現異常,則保證資料一致性執行下面的copy操作 if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } //清理無用的元素, 通知GC回收 if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }
final修飾的變數指的是同一個引用, 為了後面保持資料的一致性。
此方法,想保留Collection c中的元素時, complement值為true; 想移除c中的元素時, complement值為false。這樣就分別變成了retainAll和removeAll方法。
swap:交換arrayList中的某兩個位置的
二、LinkedList源碼分析(JDK7)
LinkedList即鏈表, 相對於順序表, 鏈表格儲存體資料不需要使用地址連續的記憶體單元。減少了修改容器結構而帶來的移動元素的問題,順序訪問相對高效。
1、結點(Node)的定義
JDK中的LinkedList是雙向鏈表, 每個結點分別存有上一個結點和下一個結點的資訊。它的定義如下:
private static class Node<E> { E item; Node<E> next; Node<E> prev; Node<E> (Node<E> prev, E element, Node<E> next) { this.item = element; this.next = next; this.prev = prev; }}
2、LinkedList構造以及初始化
成員: LinkedList中維護了3個成員變數, 用以記錄鏈表中結點的個數, 結點的前驅以及後繼
transient int size = 0;transient Node<E> first;transient Node<E> last;
建構函式: 預設建構函式即構造一個空的LinkedList
或者根據其他容器進行構造, 後面我們會自己寫一個構造一個有序的鏈表
public LinkedList(Collection<? extends E> c) { this(); addAll(c);}
這裡給出一點補充, 關於泛型修飾符? super T 與 ? extends T的區別,參見這篇文章泛型中? super T和? extends T的區別
3、LinkedList的結構操作
頭插法: 即在鏈表頭插入一個元素
private void linkFirst(E e) { final Node<E> f = first; final Node<E> newNode = new Node<>(null, e, f); first = newNode; //判斷是否是空鏈表 if (f == null) last = newNode; else f.prev = newNode; size++; modCount++; }
尾插法: 即在鏈表尾部插入一個元素
void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
插入到當前結點之前: 找當前結點的前驅
void linkBefore(E e, Node<E> succ) { //確定當然結點非空 final Node<E> pred = succ.prev; final Node<E> newNode = new Node<>(pred, e, succ); succ.prev = newNode; //判斷當前結點是否是第一個結點 if (pred == null) first = newNode; else pred.next = newNode; size++; modCount++; }
頭刪法: 刪除鏈表的第一個結點
private E unlinkFirst(Node<E> f) { // assert f == first && f != null; final E element = f.item; final Node<E> next = f.next; f.item = null; f.next = null; // help GC first = next; if (next == null) last = null; else next.prev = null; size--; modCount++; return element; }
尾刪法:刪除鏈表的最後一個結點
private E unlinkLast(Node<E> l) { //保證l==last 並且l != null final E element = l.item; final Node<E> prev = l.prev; l.item = null; l.prev = null; // help GC last = prev; if (prev == null) first = null; else prev.next = null; size--; modCount++; return element; }
4、保持List介面與Deque的一致性
List介面允許使用下標來實現對容器的隨機訪問,對於數組這種實現隨機訪問是很容易的。對於鏈表,JDK也從邏輯上利用鏈表中結點的計數給出了隨機訪問的實現
Node<E> node(int index) { //確保index的正確性 if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
index 屬於前半部分的計數, 從頭遍曆尋找。index屬於後半部分的計數, 從末尾遍曆尋找。充分利用雙向鏈表的特點。
因此,add(int index, T t), get(int), set(int)等方法就可以很容易的實現。
LinkedList實現了Deque介面, 也就是LinkedList實現了雙端隊列容器的方法,下面給出一些API的總結。
5、LinkedList的遍曆
既然LinkedList是雙向鏈表, 自然就可以前後遍曆。與ArrayList同樣, 涉及到多線程操作容器的時候LinkedList也會出現fail-fast問題。
對於fail-fast問題上篇已經講解過, 這裡就不說了。
關於迭代器,LinkedList有listIterator雙向迭代器, 和DescendingIterator逆序迭代器。都很簡單。源碼不在分析
如果遍曆元素的話, 隨機訪問的代價是比較大得。
三、LinkedList,ArrayList, Vector總結
1、LinkedList與ArrayList
ArrayList是實現了基於動態數組的資料結構,LinkedList基於鏈表的資料結構。
對於隨機訪問get和set,ArrayList覺得優於LinkedList,因為LinkedList要移動指標。
對於新增和刪除操作add和remove,LinedList比較佔優勢,因為ArrayList要移動資料。這一點要看實際情況的。若只對單條資料插入或刪除,ArrayList的速度反而優於LinkedList。但若是批量隨機的插入刪除資料,LinkedList的速度大大優於ArrayList. 因為ArrayList每插入一條資料,要移動插入點及之後的所有資料。
2、ArrayList與Vector
vector是線程同步的,所以它也是安全執行緒的,而arraylist是線程非同步,是不安全的。如果不考慮到線程的安全因素,一般用arraylist效率比較高。
如果集合中的元素的數目大於目前集合數組的長度時,vector增長率為目前數組長度的100%,而arraylist增長率為目前數組長度的50%.如過在集合中使用資料量比較大的資料,用vector有一定的優勢。
如果尋找一個指定位置的資料,vector和arraylist使用的時間是相同的,都是0(1),這個時候使用vector和arraylist都可以。而如果移動一個指定位置的資料花費的時間為0(n-i)n為總長度,這個時候就應該考慮到使用linklist,因為它移動一個指定位置的資料所花費的時間為0(1),而查詢一個指定位置的資料時花費的時間為0(i)。
ArrayList 和Vector是採用數組方式儲存資料,此數組元素數大於實際儲存的資料以便增加和插入元素,都允許直接序號索引元素,但是插入資料要設計到數組元素移動等記憶體操作,所以索引資料快插入資料慢,Vector由於使用了synchronized方法(安全執行緒)所以效能上比ArrayList要差,LinkedList使用雙向鏈表實現儲存,按序號索引資料需要進行向前或向後遍曆,但是插入資料時只需要記錄本項的前後項即可,所以插入數度較快!