JDK源碼(四)ArrayList集合

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    /**
     * 序列化版本號8683452581122892189L
     */
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 默認容量10
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 一個空數組
     * 當用戶指定該 ArrayList 容量爲 0 時,返回該空數組
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 一個空數組實例
     * - 當用戶沒有指定 ArrayList 的容量時(即調用無參構造函數),返回的是該數組==>剛創建一個 ArrayList 時,其內數據量爲 0。
     * - 當用戶第一次添加元素時,該數組將會擴容,變成默認容量爲 10(DEFAULT_CAPACITY) 的一個數組===>通過  ensureCapacityInternal() 實現
     * 它與 EMPTY_ELEMENTDATA 的區別就是:該數組是默認返回的,而後者是在用戶指定容量爲 0 時返回
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * ArrayList基於數組實現,用該數組保存數據, ArrayList 的容量就是該數組的長度
     * - 該值爲 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 時,當第一次添加元素進入 ArrayList 中時,數組將擴容值 DEFAULT_CAPACITY(10)
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * ArrayList實際存儲的數據數量
     */
    private int size;

    /**
     *
     * 帶參構造,手動設置容器初始大小,若實例化時能確定大小,最好別使用默認擴展容量,將提高運行效率
     * @param initialCapacity 列表的初始容量
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];//初始容量大於0,實例化數組
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;//初始化等於0,將空數組賦給elementData
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);//初始容量小於,拋異常
        }
    }



    /**
     * 無參構造,使用默認容器初始化大小10
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 帶參構造器,將參數集合用數組工具類轉成數組,
     * 並存入緩衝數組,對緩衝數組進行校驗.
     * 若轉換後的數組並非object數組(內嵌套無法直接引用情況下),
     * 則使用數組工具類將該數組使用深度拷貝
     * @param c
     */
    public ArrayList(Collection<? extends E> c) {
        //轉換成數組
        elementData = c.toArray();
        //把轉化後的Object[]數組長度賦值給當前ArrayList的size,並判斷是否爲0
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            // 這句話意思是:c.toArray 可能不會返回 Object[],可以查看 java 官方編號爲 6260652 的 bug
            if (elementData.getClass() != Object[].class)
                //複製指定數組,使elementData具有指定長度
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 替換爲空數組
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * 去除多餘的數組申請空間,在內存緊張時會用到
     */
    public void trimToSize() {
        // modCount 是 AbstractList 的屬性值:protected transient int modCount = 0;
        // [問] modCount 有什麼用?
        modCount++;

        // 當實際大小 < 數組緩衝區大小時
        // 如調用默認構造函數後,剛添加一個元素,此時 elementData.length = 10,而 size = 1
        // 通過這一步,可以使得空間得到有效利用,而不會出現資源浪費的情況
        if (size < elementData.length) {
            // 注意這裏:這裏的執行順序不是 (elementData = (size == 0) ) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size);
            // 而是:elementData = ((size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size));
            // 這裏是運算符優先級的語法
            // 調整數組緩衝區 elementData,變爲實際存儲大小 Arrays.copyOf(elementData, size)
            //先判斷size是否爲0,如果爲0:實際存儲爲EMPTY_ELEMENTDATA,如果有數據就是Arrays.copyOf(elementData, size)
            elementData = (size == 0)
                    ? EMPTY_ELEMENTDATA
                    : Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 對底層緩衝數組進行擴容的優化方法,如果已知該ArrayList容量,
     * 則可執行一次性擴容,
     * 否則將在數組add的過程中進行動態擴容,效率較低
     * @param minCapacity
     */
    public void ensureCapacity(int minCapacity) {
        // 最小擴充容量,默認是 10
        //這句就是:判斷是不是空的ArrayList,如果是的最小擴充容量10,否則最小擴充量爲0
        //上面無參構造函數創建後,當元素第一次被加入時,擴容至默認容量 10,就是靠這句代碼
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            ? 0
            : DEFAULT_CAPACITY;

        // 若用戶指定的最小容量 > 最小擴充容量,則以用戶指定的爲準,否則還是 10
        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    /**
     * 私有方法:明確 ArrayList 的容量,提供給本類使用的方法
     * - 用於內部優化,保證空間資源不被浪費:尤其在 add() 方法添加時起效
     * @param minCapacity    指定的最小容量
     */
    private void ensureCapacityInternal(int minCapacity) {
        // 若 elementData == {},則取 minCapacity 爲 默認容量和參數 minCapacity 之間的最大值
        // 注:ensureCapacity() 是提供給用戶使用的方法,在 ArrayList 的實現中並沒有使用
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    /**
     * 私有方法:明確 ArrayList 的容量
     * - 用於內部優化,保證空間資源不被浪費:尤其在 add() 方法添加時起效
     * @param minCapacity    指定的最小容量
     */
    private void ensureExplicitCapacity(int minCapacity) {
        // 將“修改統計數”+1,該變量主要是用來實現fail-fast機制的
        modCount++;
        // 防止溢出代碼:確保指定的最小容量 > 數組緩衝區當前的長度
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * 數組緩衝區最大存儲容量
     * - 一些 VM 會在一個數組中存儲某些數據--->爲什麼要減去 8 的原因
     * - 嘗試分配這個最大存儲容量,可能會導致 OutOfMemoryError(當該值 > VM 的限制時)
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 擴容
     * @param minCapacity
     */
    private void grow(int minCapacity) {
        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);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    /**
     * 被grow方法調用,擴容爲最大
     * @param minCapacity
     * @return
     */
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // 參數錯誤,拋出異常
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;//返回最大容量
    }
    /**
     * 定義size方法,應返回size大小,最大值爲Integer.MAX_VALUE
     * @return
     */
    public int size() {
        return size;
    }
    /**
     * 定義isEmpty方法,用於返回是否爲空
     * 如果不包含元素,則返回true
     * @return
     */
    @Contract(pure = true)
    public boolean isEmpty() {
        return size == 0;
    }
    /**
     * 定義contains方法,判斷一個obj是否屬於此集合
     * 如不是集合,則返回true
     * @param o
     * @return
     */
    @Contract(pure = true)
    public boolean contains(Object o) {
        // 根據 indexOf() 的值(索引值)來判斷,大於等於 0 就包含
        // 注意:等於 0 的情況不能漏,因爲索引號是從 0 開始計數的
        return indexOf(o) >= 0;
    }

    /**
     * 順序查找,返回元素的最低索引值(最首先出現的索引位置)
     * @return 存在?最低索引值:-1
     */
    public int indexOf(@Nullable 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;
    }


    /**
     * 逆序查找,返回元素的最低索引值(最首先出現的索引位置)
     * @return 存在?最低索引值:-1
     */
    public int lastIndexOf(@Nullable Object o) {
        if (o == null) {//查詢null
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {//倒敘查詢
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /**
     * 實現的有Cloneable接口,深度複製:對拷貝出來的 ArrayList 對象的操作,不會影響原來的 ArrayList
     * @return 一個克隆的 ArrayList 實例(深度複製的結果)
     */
    public Object clone() {
        try {
            // Object 的克隆方法:會複製本對象及其內所有基本類型成員和 String 類型成員,但不會複製對象成員、引用對象
            ArrayList<?> v = (ArrayList<?>) super.clone();
            // 對需要進行復制的引用變量,進行獨立的拷貝:將存儲的元素移入新的 ArrayList 中
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }


    /**
     * 返回 ArrayList 的 Object 數組
     * - 包含 ArrayList 的所有儲存元素
     * - 對返回的該數組進行操作,不會影響該 ArrayList(相當於分配了一個新的數組)==>該操作是安全的
     * - 元素存儲順序與 ArrayList 中的一致
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }


    /**
     * 返回 ArrayList 元素組成的數組
     * @param a 需要存儲 list 中元素的數組
     * 若 a.length >= list.size,則將 list 中的元素按順序存入 a 中,然後 a[list.size] = null, a[list.size + 1] 及其後的元素依舊是 a 的元素
     * 否則,將返回包含list 所有元素且數組長度等於 list 中元素個數的數組
     * 注意:若 a 中本來存儲有元素,則 a 會被 list 的元素覆蓋,且 a[list.size] = null
     * @return
     * @throws ArrayStoreException 當 a.getClass() != list 中存儲元素的類型時
     * @throws NullPointerException 當 a 爲 null 時
     */
    public <T> T[] toArray(@NotNull T[] a) {
        // 若數組a的大小 < ArrayList的元素個數,則新建一個T[]數組,
        // 數組大小是"ArrayList的元素個數",並將“ArrayList”全部拷貝到新數組中
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        // 若數組a的大小 >= ArrayList的元素個數,則將ArrayList的全部元素都拷貝到數組a中
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }


    /**
     * 返回在索引爲 index 的元素:數組的隨機訪問
     * - 默認包訪問權限
     *
     * 封裝粒度很強,連數組隨機取值都封裝爲一個方法。
     * 主要是避免每次取值都要強轉===>設置值就沒有封裝成一個方法,因爲設置值不需要強轉
     * @param index
     * @return
     */
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     * List要求,定義get方法,獲取指定index的值
     * @param index
     * @return
     */
    @Contract(pure = true)
    public E get(int index) {
        //內部的index超限檢測方法
        rangeCheck(index);
        return elementData(index);
    }

    /**
     * 設置 index 位置元素的值
     * @param index 索引值
     * @param element 需要存儲在 index 位置的元素值
     * @return 替換前在 index 位置的元素值
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        rangeCheck(index);//越界檢查

        E oldValue = elementData(index);//獲取舊數值
        elementData[index] = element;
        return oldValue;
    }

    /**
     *增加指定的元素到ArrayList的最後位置
     * @param e 要添加的元素
     * @return
     */
    public boolean add(E e) {
        // 確定ArrayList的容量大小---嚴謹
        // 注意:size + 1,保證資源空間不被浪費,
        // ☆☆☆按當前情況,保證要存多少個元素,就只分配多少空間資源
        ensureCapacityInternal(size + 1);
        elementData[size++] = e;
        return true;
    }


    /**
     *
     *在這個ArrayList中的指定位置插入指定的元素,
     *  - 在指定位置插入新元素,原先在 index 位置的值往後移動一位
     * @param index 指定位置
     * @param element 指定元素
     * @throws IndexOutOfBoundsException
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);//判斷角標是否越界
        //看上面的,size+1,保證資源空間不浪費,按當前情況,保證要存多少元素,就只分配多少空間資源
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //第一個是要複製的數組,第二個是從要複製的數組的第幾個開始,
        // 第三個是複製到那,四個是複製到的數組第幾個開始,最後一個是複製長度
        //即在數組elementData從index位置開始,複製到index+1位置,共複製size-index個元素
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

    /**
     * 移除指定位置的元素
     * index 之後的所有元素依次左移一位
     * @param index 指定位置
     * @return 被移除的元素
     * @throws IndexOutOfBoundsException
     */
    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; // 讓GC完成它的工作
        return oldValue;
    }
    /**
     * 移除list中指定的第一個元素(符合條件索引最低的)
     * 如果list中不包含這個元素,這個list不會改變
     * 如果包含這個元素,index 之後的所有元素依次左移一位
     * @param o 這個list中要被移除的元素
     * @return
     */
    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;
    }
    /**
     * 快速刪除第 index 個元素
     * 和public E remove(int index)相比
     * 私有方法,跳過檢查,不返回被刪除的值
     * @param index 要刪除的腳標
     */
    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; // 讓GC完成它的工作
    }

    /**
     * 移除list中的所有元素,這個list表將在調用之後置空
     * - 它會將數組緩衝區所以元素置爲 null
     * - 清空後,我們直接打印 list,卻只會看見一個 [], 而不是 [null, null, ….] ==> toString() 和 迭代器進行了處理
     */
    public void clear() {
        modCount++;
        // 讓GC完成它的工作
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }

    /**
     * 將一個集合的所有元素順序添加(追加)到 lits 末尾
     * - ArrayList 是線程不安全的。
     * - 該方法沒有加鎖,當一個線程正在將 c 中的元素加入 list 中,但同時有另一個線程在更改 c 中的元素,可能會有問題
     * @param c  要追加的集合
     * @return <tt>true</tt> ? list 元素個數有改變時,成功:失敗
     * @throws NullPointerException 當 c 爲 null 時
     */
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;//要添加元素的個數
        ensureCapacityInternal(size + numNew);//擴容
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

    /**
     * 從 List 中指定位置開始插入指定集合的所有元素,
     * -list中原來位置的元素向後移
     * - 並不會覆蓋掉在 index 位置原有的值
     * - 類似於 insert 操作,在 index 處插入 c.length 個元素(原來在此處的 n 個元素依次右移)
     * @param index 插入指定集合的索引
     * @param c 要添加的集合
     * @return ? list 元素個數有改變時,成功:失敗
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        //index>size拋出異常
        rangeCheckForAdd(index);
        Object[] a = c.toArray();//是將list直接轉爲Object[] 數組
        int numNew = a.length;//要添加集合的元素數量
        ensureCapacityInternal(size + numNew);  // 擴容
        int numMoved = size - index;//list中要移動的數量
        if (numMoved > 0)
            //先將ArrayList中從index開始的numMoved個元素移動到起始位置爲index+numNew的後面去
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

        //再將c中的numNew個元素複製到起始位置爲index的存儲空間中去
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

    /**
     * 移除list中 [fromIndex,toIndex) 的元素
     * - 從toIndex之後(包括toIndex)的元素向前移動(toIndex-fromIndex)個元素
     * -如果(toIndex==fromIndex)這個操作沒有影響
     * @throws IndexOutOfBoundsException if {@code fromIndex} or
     *         {@code toIndex} is out of range
     *         ({@code fromIndex < 0 ||
     *          fromIndex >= size() ||
     *          toIndex > size() ||
     *          toIndex < fromIndex})
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;//要移動的數量
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);
        // 刪除後,list 的長度
        int newSize = size - (toIndex-fromIndex);
        //將失效元素置空,方便gc回收
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

    /**
     * 內部的index超限檢測方法,當index超過size的時候,拋出index超限異常,在本類中被多次調用
     * @param index
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 越界異常
     * @param index
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 構建IndexOutOfBoundsException詳細消息
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }


    /**
     * 移除list中指定集合包含的所有元素
     * @param c 要從list中移除的指定集合
     * @return {@code true} if this list changed as a result of the call
     * @throws ClassCastException 如果list中的一個元素的類和指定集合不兼容
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException  如果list中包含一個空元素,而指定集合中不允許有空元素
     */
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);//判斷集合是否爲空,如果爲空報NullPointerException
        return batchRemove(c, false);//批量移除c集合的元素,第二個參數:是否採補集
    }
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    /**
     * 批處理移除
     * @param c 要移除的集合
     * @param complement 是否是補集
     * 如果true:移除list中除了c集合中的所有元素
     * 如果false:移除list中 c集合中的元素
     */
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            //遍歷數組,並檢查這個集合是否對應值,移動要保留的值到數組前面,w最後值爲要保留的值得數量
            //如果保留:將相同元素移動到前段,如果不保留:將不同的元素移動到前段
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            //最後 r=size 注意for循環中最後的r++
            //     w=保留元素的大小
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            //r!=size表示可能出錯了,
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            //如果w==size:表示全部元素都保留了,所以也就沒有刪除操作發生,所以會返回false;反之,返回true,並更改數組
            //而 w!=size;即使try拋出異常,也能正常處理異常拋出前的操作,因爲w始終要爲保留的前半部分,數組也不會因此亂序
            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;
    }

    /**
     *  私有方法
     *  將ArrayList實例序列化
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // 寫入所有元素數量的任何隱藏的東西
        int expectedModCount = modCount;
        s.defaultWriteObject();

        //寫入clone行爲的容量大小
        s.writeInt(size);

        //以合適的順序寫入所有的元素
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * 私有方法
     * 從反序列化中重構ArrayList實例
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;

        //讀出大小和隱藏的東西
        s.defaultReadObject();

        // 從輸入流中讀取ArrayList的size
        s.readInt(); // ignored

        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            ensureCapacityInternal(size);

            Object[] a = elementData;
            // 從輸入流中將“所有的元素值”讀出
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

    /**
     * 返回從指定索引開始到結束的帶有元素的list迭代器
     */
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * 返回從0索引開始到結束的帶有元素的list迭代器
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 以一種合適的排序返回一個iterator到元素的結尾
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * Itr是AbstractList.Itr的優化版本
     * 爲什麼會報ConcurrentModificationException異常?
     * 1. Iterator 是工作在一個獨立的線程中,並且擁有一個 mutex 鎖。
     * 2. Iterator 被創建之後會建立一個指向原來對象的單鏈索引表,當原來的對象數量發生變化時,
     * 這個索引表的內容不會同步改變,所以當索引指針往後移動的時候就找不到要迭代的對象,
     * 3. 所以按照 fail-fast 原則 Iterator 會馬上拋出 java.util.ConcurrentModificationException 異常。
     * 4. 所以 Iterator 在工作的時候是不允許被迭代的對象被改變的。
     * 但你可以使用 Iterator 本身的方法 remove() 來刪除對象,
     * 5. Iterator.remove() 方法會在刪除當前迭代對象的同時維護索引的一致性。
     */
    private class Itr implements Iterator<E> {
        int cursor;       // 下一個元素返回的索引
        int lastRet = -1; // 最後一個元素返回的索引  -1 if no such
        int expectedModCount = modCount;

        /**
         * 是否有下一個元素
         */
        public boolean hasNext() {
            return cursor != size;
        }

        /**
         * 返回list中的值
         */
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;//i當前元素的索引
            if (i >= size)//第一次檢查:角標是否越界越界
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)//第二次檢查,list集合中數量是否發生變化
                throw new ConcurrentModificationException();
            cursor = i + 1;//下一個元素的索引
            return (E) elementData[lastRet = i];//最後一個元素返回的索引
        }


        /**
         * 移除集合中的元素
         */
        public void remove() {
            if (lastRet < 0)//最後一個元素返回的索引
                throw new IllegalStateException();
            checkForComodification();

            try {
                //移除list中的元素
                ArrayList.this.remove(lastRet);
                //由於cursor比lastRet大1,所有這行代碼是指指針往回移動一位
                cursor = lastRet;
                //將最後一個元素返回的索引重置爲-1
                lastRet = -1;
                //重新設置了expectedModCount的值,避免了ConcurrentModificationException的產生
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }


        /**
         * jdk 1.8中使用的方法
         * 將list中的所有元素都給了consumer,可以使用這個方法來取出元素
         */
        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(@NotNull 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();
        }

        /**
         * 檢查modCount是否等於expectedModCount
         * 在 迭代時list集合的元素數量發生變化時會造成這兩個值不相等
         */
        final void checkForComodification() {
            //當expectedModCount和modCount不相等時,就拋出ConcurrentModificationException
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    /*------------------------------------- Itr 結束 -------------------------------------------*/

    /**
     * AbstractList.ListItr 的優化版本
     * ListIterator 與普通的 Iterator 的區別:
     * - 它可以進行雙向移動,而普通的迭代器只能單向移動
     * - 它可以添加元素(有 add() 方法),而後者不行
     */
    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;
        }
        /**
         * 獲取 cursor 前一個元素的索引
         * - 是 cursor 前一個,而不是當前元素前一個的索引。
         * - 若調用 next() 後馬上調用該方法,則返回的是當前元素的索引。
         * - 若調用 next() 後想獲取當前元素前一個元素的索引,需要連續調用兩次該方法。
         */
        public int previousIndex() {
            return cursor - 1;
        }

        /**
         * 返回 cursor 前一元素
         */
        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            if (i < 0)//第一次檢查:索引是否越界
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)//第二次檢查
                throw new ConcurrentModificationException();
            cursor = i;//cursor回移
            return (E) elementData[lastRet = i];//返回 cursor 前一元素
        }

        /**
         * 將數組的最後一個元素,設置成元素e
         */
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
            try {
                //將數組最後一個元素,設置成元素e
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        /**
         * 添加元素
         */
        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;//當前元素的索引後移一位
                ArrayList.this.add(i, e);//在i位置上添加元素e
                cursor = i + 1;//cursor後移一位
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }
    /*------------------------------------- ListItr 結束 -------------------------------------------*/


    /**
     * 獲取從 fromIndex 到 toIndex 之間的子集合(左閉右開區間)
     * - 若 fromIndex == toIndex,則返回的空集合
     * - 對該子集合的操作,會影響原有集合
     * - 當調用了 subList() 後,若對原有集合進行刪除操作(刪除subList 中的首個元素)時,會拋出異常 java.util.ConcurrentModificationException
     *  這個和Itr的原因差不多由於modCount發生了改變,對集合的操作需要用子集合提供的方法
     * - 該子集合支持所有的集合操作
     *
     * 原因看 SubList 內部類的構造函數就可以知道
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws IllegalArgumentException {@inheritDoc}
     */
    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

    /**
     * 檢查傳入索引的合法性
     * 注意[fromIndex,toIndex)
     */
    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > size)//由於是左閉右開的,所以toIndex可以等於size
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
    }

    /**
     * 私有類
     * 嵌套內部類:也實現了 RandomAccess,提供快速隨機訪問特性
     * 這個是通過映射來實現的
     */
    private class SubList extends AbstractList<E> implements RandomAccess {
        private final AbstractList<E> parent; //實際傳入的是ArrayList本身
        private final int parentOffset;// 相對於父集合的偏移量,其實就是 fromIndex
        private final int offset;// 偏移量,默認是 0
        int size;//SubList中的元素個數

        SubList(AbstractList<E> parent,
                int offset, int fromIndex, int toIndex) {
            // 看到這部分,就理解爲什麼對 SubList 的操作,會影響父集合---> 因爲子集合的處理,僅僅是給出了一個映射到父集合相應區間的引用
            // 再加上 final,的修飾,就能明白爲什麼進行了截取子集合操作後,父集合不能刪除 SubList 中的首個元素了--->offset 不能更改
            this.parent = parent;
            this.parentOffset = fromIndex;//原來的偏移量
            this.offset = offset + fromIndex;//加了offset的偏移量
            this.size = toIndex - fromIndex;
            this.modCount = ArrayList.this.modCount;
        }



        /**
         * 設置新值,返回舊值
         */
        public E set(int index, E e) {
            rangeCheck(index);//越界檢查
            checkForComodification();//檢查
            //從這一條語句可以看出:對子類添加元素,是直接操作父類添加的
            E oldValue = ArrayList.this.elementData(offset + index);
            ArrayList.this.elementData[offset + index] = e;
            return oldValue;
        }

        /**
         * 獲取指定索引的元素
         */
        @Contract(pure = true)
        public E get(int index) {
            rangeCheck(index);
            checkForComodification();
            return ArrayList.this.elementData(offset + index);
        }

        /**
         * 返回元素的數量
         */
        public int size() {
            checkForComodification();
            return this.size;
        }

        /**
         * 指定位置添加元素
         */
        public void add(int index, E e) {
            rangeCheckForAdd(index);
            checkForComodification();
            parent.add(parentOffset + index, e);
            this.modCount = parent.modCount;
            this.size++;
        }
        /**
         * 移除指定位置的元素
         */
        public E remove(int index) {
            rangeCheck(index);
            checkForComodification();
            //從這裏可以看出,先通過index拿到在原來數組上的索引,再調用父類的添加方法實現添加
            E result = parent.remove(parentOffset + index);
            this.modCount = parent.modCount;
            this.size--;
            return result;
        }

        /**
         * 移除subList中的[fromIndex,toIndex)之間的元素
         */
        protected void removeRange(int fromIndex, int toIndex) {
            checkForComodification();
            parent.removeRange(parentOffset + fromIndex,
                               parentOffset + toIndex);
            this.modCount = parent.modCount;
            this.size -= toIndex - fromIndex;
        }
        /**
         * 添加集合中的元素到subList結尾
         * @param c
         * @return
         */
        public boolean addAll(Collection<? extends E> c) {
            //調用父類的方法添加集合元素
            return addAll(this.size, c);
        }

        /**
         * 在subList指定位置,添加集合中的元素
         */
        public boolean addAll(int index, Collection<? extends E> c) {
            rangeCheckForAdd(index);//越界檢查
            int cSize = c.size();
            if (cSize==0)
                return false;

            checkForComodification();
            //調用父類的方法添加
            parent.addAll(parentOffset + index, c);
            this.modCount = parent.modCount;
            this.size += cSize;
            return true;
        }

        /**
         * subList中的迭代器
         */
        public Iterator<E> iterator() {
            return listIterator();
        }

        /**
         * 返回從指定索引開始到結束的帶有元素的list迭代器
         */
        public ListIterator<E> listIterator(final int index) {
            checkForComodification();
            rangeCheckForAdd(index);
            final int offset = this.offset;//偏移量

            return new ListIterator<E>() {
                int cursor = index;
                int lastRet = -1;//最後一個元素的下標
                int expectedModCount = ArrayList.this.modCount;

                public boolean hasNext() {
                    return cursor != SubList.this.size;
                }

                @SuppressWarnings("unchecked")
                public E next() {
                    checkForComodification();
                    int i = cursor;
                    if (i >= SubList.this.size)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i + 1;
                    return (E) elementData[offset + (lastRet = i)];
                }

                public boolean hasPrevious() {
                    return cursor != 0;
                }
                //jdk8的方法
                @SuppressWarnings("unchecked")
                public E previous() {
                    checkForComodification();
                    int i = cursor - 1;
                    if (i < 0)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i;
                    return (E) elementData[offset + (lastRet = i)];
                }

                @SuppressWarnings("unchecked")
                public void forEachRemaining(Consumer<? super E> consumer) {
                    Objects.requireNonNull(consumer);
                    final int size = SubList.this.size;
                    int i = cursor;
                    if (i >= size) {
                        return;
                    }
                    final Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length) {
                        throw new ConcurrentModificationException();
                    }
                    while (i != size && modCount == expectedModCount) {
                        consumer.accept((E) elementData[offset + (i++)]);
                    }
                    // update once at end of iteration to reduce heap write traffic
                    lastRet = cursor = i;
                    checkForComodification();
                }

                public int nextIndex() {
                    return cursor;
                }

                public int previousIndex() {
                    return cursor - 1;
                }

                public void remove() {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        SubList.this.remove(lastRet);
                        cursor = lastRet;
                        lastRet = -1;
                        expectedModCount = ArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void set(E e) {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        ArrayList.this.set(offset + lastRet, e);
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void add(E e) {
                    checkForComodification();

                    try {
                        int i = cursor;
                        SubList.this.add(i, e);
                        cursor = i + 1;
                        lastRet = -1;
                        expectedModCount = ArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                final void checkForComodification() {
                    if (expectedModCount != ArrayList.this.modCount)
                        throw new ConcurrentModificationException();
                }
            };
        }


        //subList的方法,同樣可以再次截取List同樣是使用映射方式
        public List<E> subList(int fromIndex, int toIndex) {
            subListRangeCheck(fromIndex, toIndex, size);
            return new SubList(this, offset, fromIndex, toIndex);
        }

        private void rangeCheck(int index) {
            if (index < 0 || index >= this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

        private void rangeCheckForAdd(int index) {
            if (index < 0 || index > this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

        private String outOfBoundsMsg(int index) {
            return "Index: "+index+", Size: "+this.size;
        }

        private void checkForComodification() {
            if (ArrayList.this.modCount != this.modCount)
                throw new ConcurrentModificationException();
        }

        /**
         * subList方法:獲取一個分割器
         * - fail-fast
         * - late-binding:後期綁定
         * - java8 開始提供
         */
        public Spliterator<E> spliterator() {
            checkForComodification();
            return new ArrayListSpliterator<E>(ArrayList.this, offset,
                                               offset + this.size, this.modCount);
        }
    }

    @Override
    public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            //這裏將所有元素都接受到Consumer中了,所有可以使用1.8中的方法直接獲取每一個元素
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * 獲取一個分割器
     * - fail-fast 機制和itr,subList一個機制
     * - late-binding:後期綁定
     * - java8 開始提供
     * @return a {@code Spliterator} over the elements in this list
     * @since 1.8
     */
    @Override
    public Spliterator<E> spliterator() {
        return new ArrayListSpliterator<>(this, 0, -1, 0);
    }

    /**
     * 基於索引的、二分的、懶加載的分割器
     * @param <E>
     */
    static final class ArrayListSpliterator<E> implements Spliterator<E> {
        //用於存放ArrayList對象
        private final ArrayList<E> list;
        private int index;//起始位置(包含),advance/split操作時會修改
        private int fence; //結束位置(不包含),-1 表示到最後一個元素
        private int expectedModCount;//用於存放list的modCount

        /**
         * 默認的起始位置是0,默認的結束位置是-1
         * @param list
         * @param origin
         * @param fence
         * @param expectedModCount
         */
        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
                             int expectedModCount) {
            this.list = list; // OK if null unless traversed
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        /**
         * 在第一次使用時實例化結束位置
         * @return
         */
        private int getFence() { // initialize fence to size on first use
            int hi; // (a specialized variant appears in method forEach)
            ArrayList<E> lst;
            //fence<0時(第一次初始化時,fence纔會小於0):
            if ((hi = fence) < 0) {
                //如果list集合中沒有元素
                if ((lst = list) == null)
                    //list 爲 null時,fence=0
                    hi = fence = 0;
                else {
                    //否則,fence = list的長度。
                    expectedModCount = lst.modCount;
                    hi = fence = lst.size;
                }
            }
            return hi;
        }


        /**
         * 分割list,返回一個新分割出的spliterator實例
         * 相當於二分法,這個方法會遞歸
         * 1.ArrayListSpliterator本質上還是對原list進行操作,只是通過index和fence來控制每次處理範圍
         * 2.也可以得出,ArrayListSpliterator在遍歷元素時,不能對list進行結構變更操作,否則拋錯。
         *
         * @return
         */
        public ArrayListSpliterator<E> trySplit() {
            //hi:結束位置(不包括)  lo:開始位置   mid:中間位置
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            //當lo>=mid,表示不能在分割,返回null
            //當lo<mid時,可分割,切割(lo,mid)出去,同時更新index=mid
            /**如:   | 0 | 1 | 2 | 3 | 4 | 5 |    數組長度爲6 的進行 split
             *   結束角標 hi:6    開始角標lo:0    mid:3    lo<mid
             *   [0,3)  同時 lo:3   hi:6    mid:4
             *   [3,4)  同時  lo:4   hi:6   mid:5
             *   [4,5)  同時   lo:5   hid:6   mid:5
             *   null
             */
            return (lo >= mid) ? null : // divide range in half unless too small
                new ArrayListSpliterator<E>(list, lo, index = mid,
                                            expectedModCount);
        }


        /**
         * 返回true 時,只表示可能還有元素未處理
         * 返回false 時,沒有剩餘元素處理了。。。
         * @param action
         * @return
         */
        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null)
                throw new NullPointerException();
            int hi = getFence(), i = index;
            if (i < hi) {
                index = i + 1;//角標前移
                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];//取出元素
                action.accept(e);
                if (list.modCount != expectedModCount)//遍歷時,結構發生變更,拋錯
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        /**
         * 順序遍歷處理所有剩下的元素
         * Consumer類型,傳入值處理
         * @param action
         */
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi, mc; // hi list的長度
            ArrayList<E> lst; Object[] a;//數組,元素集合

            if (action == null)
                throw new NullPointerException();
            //如果list不爲空 而且  list中的元素不爲空
            if ((lst = list) != null && (a = lst.elementData) != null) {
                //當fence<0時,表示fence和expectedModCount未初始化,可以思考一下這裏能否直接調用getFence(),嘿嘿?
                if ((hi = fence) < 0) {
                    mc = lst.modCount;
                    hi = lst.size;//由於上面判斷過了,可以直接將lst大小給hi(不包括)
                }
                else
                    mc = expectedModCount;
                if ((i = index) >= 0 && (index = hi) <= a.length) {
                    for (; i < hi; ++i) {//將所有元素給Consumer
                        @SuppressWarnings("unchecked") E e = (E) a[i];
                        action.accept(e);
                    }
                    if (lst.modCount == mc)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

        /**
         * 估算大小
         * @return
         */
        public long estimateSize() {
            return (long) (getFence() - index);
        }

        /**
         * 打上特徵值:、可以返回size
         * @return
         */
        public int characteristics() {
            //命令,大小,子大小
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }

    /**
     * 1.8方法
     * 根據Predicate條件來移除元素
     * 將所有元素依次根據filter的條件判斷
     * Predicate 是 傳入元素 返回 boolean 類型的接口
     */
    @Override
    public boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        int removeCount = 0;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {//如果元素滿足條件
                removeSet.set(i);//將滿足條件的角標存放到set中
                removeCount++;//移除set的數量
            }
        }
        if (modCount != expectedModCount) {//判斷是否外部修改了
            throw new ConcurrentModificationException();
        }

        // shift surviving elements left over the spaces left by removed elements
        final boolean anyToRemove = removeCount > 0;//如果有移除元素
        if (anyToRemove) {
            final int newSize = size - removeCount;//新大小
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);//i是[0,size)中不是set集合中的角標
                elementData[j] = elementData[i];//新元素
            }
            //將空元素置空
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

    /**
     * UnaryOperator 接受一個什麼類型的參數,返回一個什麼類型的參數
     * 對數組中的每一個元素進行一系列的操作,返回同樣的元素,
     * 如果 List<Student> lists  將list集合中的每一個student姓名改爲張三
     * 使用這個方法就非常方便
     * @param operator
     */
    @Override
    @SuppressWarnings("unchecked")
    public void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            //取出每一個元素給operator的apply方法
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }
    /**
     * 根據 Comparator條件進行排序
     * Comparator(e1,e2) 返回 boolean類型
     */
    @Override
    @SuppressWarnings("unchecked")
    public void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章