java集合(二)List集合之ArrayList詳解

前言:

有序列表,容許存放重複的元素;
實現類:java

    • ArrayList:數組實現,查詢快,增刪慢,輕量級;(線程不安全)
    • LinkedList:雙向鏈表實現,增刪快,查詢慢 (線程不安全)
    • Vector:數組實現,重量級 (線程安全、使用少)
    • Stack:對象棧,遵循先進後出的原則。 

1、ArrayList簡介

  ArrayList 是 java 集合框架中比較經常使用的數據結構了。繼承自 AbstractList,實現了 List 接口。底層基於數組實現容量大小動態變化。容許 null 的存在。同時還實現了 RandomAccess、Cloneable、Serializable 接口,因此ArrayList 是支持快速訪問、複製、序列化的。數組

2、成員變量

  ArrayList 底層是基於數組來實現容量大小動態變化的。安全

/** * The size of the ArrayList (the number of elements it contains). */
private int size;  // 實際元素個數
transient Object[] elementData;

  注意:上面的 size 是指 elementData 中實際有多少個元素,而 elementData.length 爲集合容量,表示最多能夠容納多少個元素。數據結構

默認初始容量大小爲 10;app

/** * Default initial capacity. */
private static final int DEFAULT_CAPACITY = 10;

  這個變量是定義在 AbstractList 中的。記錄對 List 操做的次數。主要使用是在 Iterator,是防止在迭代的過程當中集合被修改。框架

protected transient int modCount = 0;

  下面兩個變量是用在構造函數裏面的dom

/** * Shared empty array instance used for empty instances. */
private static final Object[] EMPTY_ELEMENTDATA = {}; /** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added. */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

  兩個空的數組有什麼區別呢? We distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when first element is added. 簡單來說就是第一次添加元素時知道該 elementData 從空的構造函數仍是有參構造函數被初始化的。以便確認如何擴容。函數

構造函數

無慘構造函數post

/** * Constructs an empty list with an initial capacity of ten. */
public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }

注意:註釋是說構造一個容量大小爲 10 的空的 list 集合,但構造函數了只是給 elementData 賦值了一個空的數組,實際上是在第一次添加元素時容量擴大至 10 的。ui

構造一個初始容量大小爲 initialCapacity 的 ArrayList

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); } }

由以上源碼可見: 當使用無參構造函數時是把 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 賦值給 elementData。 當 initialCapacity 爲零時則是把 EMPTY_ELEMENTDATA 賦值給 elementData。 當 initialCapacity 大於零時初始化一個大小爲 initialCapacity 的 object 數組並賦值給 elementData。

使用指定 Collection 來構造 ArrayList 的構造函數

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; } }

  將 Collection 轉化爲數組並賦值給 elementData,把 elementData 中元素的個數賦值給 size。 若是 size 不爲零,則判斷 elementData 的 class 類型是否爲 Object[],不是的話則作一次轉換。 若是 size 爲零,則把 EMPTY_ELEMENTDATA 賦值給 elementData,至關於new ArrayList(0)。

主要操做方法解析

  add 操做

public boolean add(E e) { ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_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); }

因而可知:每次添加元素到集合中時都會先確認下集合容量大小。而後將 size 自增 1。ensureCapacityInternal 函數中判斷若是 elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA 就取 DEFAULT_CAPACITY 和 minCapacity 的最大值也就是 10。這就是 EMPTY_ELEMENTDATA 與 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 的區別所在。同時也驗證了上面的說法:使用無慘構造函數時是在第一次添加元素時初始化容量爲 10 的。ensureExplicitCapacity 中對 modCount 自增 1,記錄操做次數,而後若是 minCapacity 大於 elementData 的長度,則對集合進行擴容。顯然第一次添加元素時 elementData 的長度爲零。那咱們來看看 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); }

很簡單明瞭的一個函數,默認將擴容至原來容量的 1.5 倍。可是擴容以後也不必定適用,有可能過小,有可能太大。因此纔會有下面兩個 if 判斷。若是1.5倍過小的話,則將咱們所需的容量大小賦值給newCapacity,若是1.5倍太大或者咱們須要的容量太大,那就直接拿 newCapacity = (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE 來擴容。而後將原數組中的數據複製到大小爲 newCapacity 的新數組中,並將新數組賦值給 elementData。

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++; } public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew);  // Increments modCount
    System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew);  // Increments modCount

    int numMoved = size - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; }

有以上源碼可知,add(int index, E element),addAll(Collection

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; } 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; } private void fastRemove(int index) { modCount++; 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
}

當咱們調用 remove(int index) 時,首先會檢查 index 是否合法,而後再判斷要刪除的元素是否位於數組的最後一個位置。若是 index 不是最後一個,就再次調用 System.arraycopy() 方法拷貝數組。說白了就是將從 index + 1 開始向後全部的元素都向前挪一個位置。而後將數組的最後一個位置空,size - 1。若是 index 是最後一個元素那麼就直接將數組的最後一個位置空,size - 1便可。 當咱們調用 remove(Object o) 時,會把 o 分爲是否爲空來分別處理。而後對數組作遍歷,找到第一個與 o 對應的下標 index,而後調用 fastRemove 方法,刪除下標爲 index 的元素。其實仔細觀察 fastRemove(int index) 方法和 remove(int index) 方法基本所有相同。

get操做

public E get(int index) { rangeCheck(index); return elementData(index); }

因爲 ArrayList 底層是基於數組實現的,因此獲取元素就至關簡單了,直接調用數組隨機訪問便可。

 

迭代器 iterator

有使用過集合的都知道,在用 for 遍歷集合的時候是不能夠對集合進行 remove操做的,由於 remove 操做會改變集合的大小。從而容易形成結果不許確甚至數組下標越界,更嚴重者還會拋出 ConcurrentModificationException。

 

foreach 遍歷等同於 iterator。爲了搞清楚異常緣由,咱們還必須過一遍源碼。

public Iterator<E> iterator() { return new Itr(); }

原來是直接返回一個 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
    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]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }

從源碼能夠看出,ArrayList 定義了一個內部類 Itr 實現了 Iterator 接口。在 Itr 內部有三個成員變量。 cursor:表明下一個要訪問的元素下標。 lastRet:表明上一個要訪問的元素下標。 expectedModCount:表明對 ArrayList 修改次數的指望值,初始值爲 modCount。

下面看看 Itr 的三個主要函數。

hasNext 實現比較簡單,若是下一個元素的下標等於集合的大小 ,就證實到最後了。

next 方法也不復雜,但很關鍵。首先判斷 expectedModCount 和 modCount 是否相等。而後對 cursor 進行判斷,看是否超過集合大小和數組長度。而後將 cursor 賦值給 lastRet ,並返回下標爲 lastRet 的元素。最後將 cursor 自增 1。開始時,cursor = 0,lastRet = -1;每調用一次 next 方法, cursor 和 lastRet 都會自增 1。

remove 方法首先會判斷 lastRet 的值是否小於 0,而後在檢查 expectedModCount 和 modCount 是否相等。接下來是關鍵,直接調用 ArrayList 的 remove 方法刪除下標爲 lastRet 的元素。而後將 lastRet 賦值給 cursor ,將 lastRet 從新賦值爲 -1,並將 modCount 從新賦值給 expectedModCount

 

 下面咱們一步一步來分析 Itr 的操做。如圖一所示,開始時 cursor 指向下標爲 0 的元素,lastRet 指向下標爲 -1 的元素,也就是 null。每調用一次 next,cursor 和lastRet 就分別會自增 1。當 next 返回 "C" 時,cursor 和 lastRet 分別爲 3 和 2 [圖二]。

 

此時調用 remove,注意是 ArrayList 的 remove,而不是 Itr 的 remove。會將 D E 兩個元素直接往前移動一位,最後一位置空,而且 modCount 會自增 1。從 remove 方法能夠看出。[圖三]。

 

 

 此時 cursor = 3,size = 4,沒有到數組末尾,因此循環繼續。來到 next 方法,由於上一步的 remove 方法對 modCount 作了修改 ,導致 expectedModCount 與 modCount 不相等,這就是 ConcurrentModificationException 異常的緣由所在。從例子.png中也能夠看出異常出自 ArrayList 中的內部類 Itr 中的 checkForComodification 方法。

異常的解決:

 

直接調用 iterator.remove() 便可。由於在該方法中增長了 expectedModCount = modCount 操做。可是這個 remove 方法也有弊端。

  1. 只能進行remove操做,add、clear 等 Itr 中沒有。
  2. 調用 remove 以前必須先調用 next。由於 remove 開始就對 lastRet 作了校驗。而 lastRet 初始化時爲 -1。
  3. next 以後只能夠調用一次 remove。由於 remove 會將 lastRet 從新初始化爲 -1

總結: ArrayList 底層基於數組實現容量大小動態可變。 擴容機制爲首先擴容爲原始容量的 1.5 倍。若是1.5倍過小的話,則將咱們所需的容量大小賦值給 newCapacity,若是1.5倍太大或者咱們須要的容量太大,那就直接拿 newCapacity = (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE 來擴容。 擴容以後是經過數組的拷貝來確保元素的準確性的,因此儘量減小擴容操做。 ArrayList 的最大存儲能力:Integer.MAX_VALUE。 size 爲集合中存儲的元素的個數。elementData.length 爲數組長度,表示最多能夠存儲多少個元素。 若是須要邊遍歷邊 remove ,必須使用 iterator。且 remove 以前必須先 next,next 以後只能用一次 remove。

來源:https://juejin.im/post/5a90c37af265da4e83267f8e
相關文章
相關標籤/搜索