一、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() {}或者根據其他容器進行構造, 后面我們會自己寫一個構造一個有序的鏈表
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使用雙向鏈表實現存儲,按序號索引數據需要進行向前或向后遍歷,但是插入數據時只需要記錄本項的前后項即可,所以插入數度較快!
新聞熱點
疑難解答