java源碼解讀之ArrayList

還是跟之前幾篇源碼的一樣,相關信息都寫在源碼裏面,直接祭出源碼啦~~~

package java.util;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;

/**
 * ArrayList繼承AbstractList,實現了List、RandomAccess、Cloneable與Serializable接口
 * 其中,AbstraceList提供了List接口的默認實現(個別方法爲抽象方法),List接口定義了列表必須實現的方法,
 * Cloneable接口使得ArrayList可以調用Object.clone方法返回該對象的淺拷貝,
 * RandomAccess與Serializable都是標記接口,接口內沒定義任何內容,RandomAccess表示該類支持快速隨機訪問(也
 * 就是通過下標快速訪問),而Serializable接口使得ArrayList可以被序列化與反序列化
 */

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 定義ArrayList初始容量,默認爲10
     */
    private static final int DEFAULT_CAPACITY = 10;

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

    /**
     * 一個空數組,當用戶沒有指定 ArrayList 的容量時(即調用無參構造函數),返回的是該數組
	 * 剛創建一個 ArrayList時,其內數據量爲0,當用戶第一次添加元素時,該數組將會擴容,變成
	 * 默認容量爲DEFAULT_CAPACITY(10)的一個數組
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 存儲ArrayList元素的Object數組,ArrayList的長度就是該數組的長度,一個空(不是null)的
     * ArrayList對象,其elementData字段引用將指向上面的DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * 數組,當第一個元素添加到該ArrayList中時elementData會被擴大到默認的容量DEFAULT_CAPACITY(10)
     * 該數組被transient關鍵字修飾,表明ArrayList在序列化時不對該屬性進行序列化,因此elementData的內容
     * 不能使用serialization機制來保存
     */
    transient Object[] elementData; 

    /**
     *記錄當前的ArrayList中包含多少元素
     */
    private int size;

    /**
     * 構造一個指定初始容量的ArrayList對象,當initialCapacity大於0,則直接初始化指定
     * initialCapacity大小的Object數組,當initialCapacity爲0則將使用上面定義的空
     * 數組EMPTY_ELEMENTDATA
     */
    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);
        }
    }

    /**
     * 當不指定初始容量構造ArrayList對象時,使用上面定義的空數組DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 使用一個指定Collection實現類的對象構造ArrayList對象
     */
    public ArrayList(Collection<? extends E> c) {
    	/**
    	 * 先調用Collection實現類的對象的toArray方法返回一個Object數組
    	 * 並賦予ArrayList對象的Object數組(Collection實現類的toArray
    	 * 方法返回的都是Object數組)
    	 */
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            /**
             * 若指定Collection實現類對象存在元素且返回的不是Object數
             * 組,則使用Arrays.copyOf方法將其轉爲Object數組
             */
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
        	/**
        	 * 若指定Collection實現類對象的元素爲空,則用空數組EMPTY_ELEMENTDATA替代ArrayList的Object數組
        	 */
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * 將當前ArrayList的容量設置爲當前實際元素的大小,比如當前ArrayList有10個元素,
     * 而容量爲15,調用的方法之後容量會被設置爲10
     */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 增加ArrayList對象的容量,在必要的情況下,由參數
     * 'minCapacity'指定以確保它至少能容納所有元素
     */
    public void ensureCapacity(int minCapacity) {
    	/**
    	 * 若該ArrayList實例的Object數組使用的不是默認的DEFAULTCAPACITY_EMPTY_ELEMENTDATA數組(只
    	 * 有當初始化時候ArrayList中元素爲空時纔會使用該默認數組),最小擴容量爲0,其餘默認爲10,這也是上面
    	 * 說的,當ArrayList使用的是默認的DEFAULTCAPACITY_EMPTY_ELEMENTDATA數組時,第一次添加元素數組
    	 * 會擴容到10
    	 */
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)?0: DEFAULT_CAPACITY;
        
        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
    	/**
    	 * 這個屬性是用於記錄該ArrayList實例結構改變的次數
    	 */
        modCount++;

        if (minCapacity - elementData.length > 0)
        	//對ArrayList進行擴容
            grow(minCapacity);
    }

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

    /**
     * 對ArrayList實例進行擴容
     */
    private void grow(int minCapacity) {
    	//取得擴容前Object數組的容量
        int oldCapacity = elementData.length;
        /**
         * 默認新的容量=老的容量*1.5
         */
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //若新容量依舊小於minCapacity,則新容量=minCapacity
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //若新容量大於數組最大存儲容量,則進行大容量分配
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        /**
         * 使用Arrays的copyOf方法複製元素到新的Object
         * 數組並將elementData引用指向新的Object數組 
         */
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    /**
     *返回當前的ArrayList中包含的元素數目
     */
    public int size() {
        return size;
    }

    /**
     *判斷當前ArrayList是否包含元素
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 判斷當前ArrayList對象是否包含指定元素,判斷依據是當前元素在ArrayList的位置>=0
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * 返回當前元素在ArrayList對象中的位置,若不存在則返回-1
     */
    public int indexOf(Object o) {
    	/**
    	 * 若該元素爲null,則遍歷ArrayList對象的Object數組,判斷元素的引
    	 * 用是否指向null,是則返回該元素的下標,注意,遍歷的終點是size,而
    	 * 不是Object數組的length,返回的是第一個爲null的元素的下標
    	 */
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
        	/**
        	 * 若該元素不爲null,按照上面的方式遍歷,調用對象的equals方法去判斷,
        	 * 區別於上面的==,equals方法比較的是對象的內容,而==比較的是引用指向
        	 * 的地址
        	 */
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        //若元素不存在則返回-1
        return -1;
    }

    /**
     * 返回當前元素在ArrayList對象最後的位置,不存在則返回-1,
     * 處理邏輯與indexOf方法一樣,只是遍歷方向相反而已
     */
    public int lastIndexOf(Object o) {
        if (o == 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;
    }

    /**
     * 簡單介紹淺拷貝與深拷貝的區別:
     * 淺拷貝:淺拷貝會對"主"對象進行拷貝,但不會複製主對象裏面的對象,
     * "裏面的對象"會在原來的對象和它的副本之間共享,兩個"主"對象不是
     * 獨立的,修改"裏面的對象"會互相影響(原始類型會直接拷貝)
     * 深拷貝:深拷貝是一個整個獨立的對象拷貝,是整個對象的結構都進行拷貝
     * 
     * String類型不用爲其創建深拷貝便可以對其進行共享,因爲是不可變對象
     */
    /**
     *返回當前ArrayList對象的淺拷貝,不拷貝ArrayList中元素的原型
     */
    public Object clone() {
        try {
        	/**
        	 * 直接調用Cloneable接口的clone方法複製出一個副本,然後
        	 * 把原ArrayList的元素複製到副本中
        	 */
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }

    /**
     * 將ArrayList對象的Object數組複製到一個新的Object數組中並返回
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * 將ArrayList對象中的Object數組複製到傳遞進來的數組中
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
    	/**
    	 * 若傳入數組的長度小於size,返回一個新的數組,大小爲size,類型與傳入數組相同
    	 */
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        /**
         * 所傳入數組長度與size相等,則將elementData複製到傳入數組中並返回傳入的數組
         */
        System.arraycopy(elementData, 0, a, 0, size);
        /**
         * 若傳入數組長度大於size,除了複製elementData外,還將把返回數組的第size個元素置爲null
         */
        if (a.length > size)
            a[size] = null;
        return a;
    }

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     *返回ArrayList對象指定位置上的元素
     */
    public E get(int index) {
    	/**
    	 * 檢查傳入的index是否越界,越界則拋IndexOutOfBoundsException異常
    	 */
        rangeCheck(index);
        //直接返回指定下標的數組元素
        return elementData(index);
    }

    /**
     * 使用新元素替換指定位置的舊元素,並返回舊元素
     */
    public E set(int index, E element) {
    	/**
    	 * 檢查傳入的index是否越界,越界則拋IndexOutOfBoundsException異常
    	 */
        rangeCheck(index);
        /**
         * 獲取舊元素,將新元素設置到ArrayList對
         * 象的Object數組的指定位置,返回舊元素
         */
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    /**
     * 將元素添加到ArrayList對象列表的末尾
     */
    public boolean add(E e) {
    	/**
    	 * 放入元素之前調用ensureCapacityInternal方法確保列表容量
    	 * 足夠,更多的是增加結構改變次數,若容量不足則進行擴容
    	 */
        ensureCapacityInternal(size + 1); 
        /**
         * 將元素放入數組末尾
         */
        elementData[size++] = e;
        return true;
    }

    /**
     * 將元素添加到指定下標的位置
     */
    public void add(int index, E element) {
    	/**
    	 * 檢查傳入的index是否越界,越界則拋IndexOutOfBoundsException異常
    	 */
        rangeCheckForAdd(index);
        /**
    	 * 放入元素之前調用ensureCapacityInternal方法確保列表容量
    	 * 足夠,更多的是增加結構改變次數,若容量不足則進行擴容
    	 */
        ensureCapacityInternal(size + 1);  
        /**
         * 調用System.arraycopy將elementData從index開始的size-index個元
         * 素複製到index+1至size+1的位置(即index開始的size-index個元素都向後移動一個位置)
         */
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //將元素放入index位置,size自增
        elementData[index] = element;
        size++;
    }

    /**
     * 移除ArrayList對象指定位置的元素
     */
    public E remove(int index) {
    	/**
    	 * 檢查傳入的index是否越界,越界則拋IndexOutOfBoundsException異常
    	 */
        rangeCheck(index);
        //結構改變次數加1
        modCount++;
        //獲取舊元素,以便返回
        E oldValue = elementData(index);
        //計算需要移動的元素個數
        int numMoved = size - index - 1;
        if (numMoved > 0)
        	//index+1開始的numMoved個元素向前移動一個位置
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //將指定位置上的元素置爲null
        elementData[--size] = null; // clear to let GC do its work
        //返回舊元素
        return oldValue;
    }

    /**
     * 移除ArrayList對象中第一個與指定對象相等的元素,若不存在ArrayList不發生改變,
     * 處理邏輯與indexOf方法類似,遇到匹配的對象則執行fastRemove方法移除,數組元素
     * 向前移動一個位置(當對象恰好在最後位置時不移動)
     */
    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 remove method that skips bounds checking and does not
     * return the value removed.
     */
    private void fastRemove(int index) {
    	//結構改變次數加1
        modCount++;
        //計算需要移動的元素個數
        int numMoved = size - index - 1;
        if (numMoved > 0)
        	//index+1開始的numMoved個元素向前移動一個位置
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //將指定位置上的元素置爲null
        elementData[--size] = null; // clear to let GC do its work
    }

    /**
     * 移除ArrayList對象中所有的元素,即把Object數組中的元素都移除
     */
    public void clear() {
    	//結構改變次數加1
        modCount++;
        /**
         * 遍歷Object數組,將所有位置上的元素置爲null
         */
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        //size歸零
        size = 0;
    }

    /**
     * 將指定集合裏面的元素添加到ArrayList對象列表的末尾
     */
    public boolean addAll(Collection<? extends E> c) {
    	//將指定集合裏面的元素以Object數組形式返回
        Object[] a = c.toArray();
        //計算指定集合的元素個數
        int numNew = a.length;
        /**
    	 * 放入元素之前調用ensureCapacityInternal方法確保列表容量
    	 * 足夠,更多的是增加結構改變次數,若容量不足則進行擴容
    	 */
        ensureCapacityInternal(size + numNew); 
        //調用System.arrayCopy方法將指定集合的Object數組添加到ArrayList對象的末尾
        System.arraycopy(a, 0, elementData, size, numNew);
        //更新ArrayList對象的size
        size += numNew;
        return numNew != 0;
    }

    /**
     * 將指定集合的元素添加到ArrayList指定位置後面
     */
    public boolean addAll(int index, Collection<? extends E> c) {
    	/**
    	 * 檢查傳入的index是否越界,越界則拋IndexOutOfBoundsException異常
    	 */
        rangeCheckForAdd(index);
        //將指定集合裏面的元素以Object數組形式返回
        Object[] a = c.toArray();
        //計算指定集合的元素個數
        int numNew = a.length;
        /**
    	 * 放入元素之前調用ensureCapacityInternal方法確保列表容量
    	 * 足夠,更多的是增加結構改變次數,若容量不足則進行擴容
    	 */
        ensureCapacityInternal(size + numNew);  // Increments modCount
        //計算需要移動的元素個數
        int numMoved = size - index;
        if (numMoved > 0)
        	//index開始的numMoved個元素向後移動numNew個位置
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
        //調用System.arrayCopy方法將指定集合的Object數組添加到ArrayList對象指定位置的末尾
        System.arraycopy(a, 0, elementData, index, numNew);
        //更新ArrayList對象的size
        size += numNew;
        return numNew != 0;
    }
// 0 1 2 3 4 5 6 7 8 9
//       3 4 5 6 7
// 0 1 2           8 9
    /**
     *移除ArrayList對象[fromIndex,toIndex)範圍內的元素
     */
    protected void removeRange(int fromIndex, int toIndex) {
    	//結構改變次數加1
        modCount++;
        //計算需要移動的元素個數
        int numMoved = size - toIndex;
        //toIndex開始的numMoved個元素移動到fromIndex開始的位置
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);
        //計算ArrayList對象的size
        int newSize = size - (toIndex-fromIndex);
        //遍歷ArrayList對象的Object數組,將[fromIndex,toIndex)範圍內的元素置爲null
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        //更新ArrayList對象的size
        size = newSize;
    }

    /**
     *檢查下標是否越界
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 添加元素時候檢查下標是否越界
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 返回下標越界的信息
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /**
     * 移除ArrayList對象中與指定集合元素匹配的元素
     */
    public boolean removeAll(Collection<?> c) {
    	//確保指定集合不爲null,否則拋NullPointerException異常
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    /**
	 * 保存ArrayList對象中與指定集合元素匹配的元素,即移除所有在指定集合中不包含的元素
     */
    public boolean retainAll(Collection<?> c) {
    	//確保指定集合不爲null,否則拋NullPointerException異常
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    /**
     * complement爲true時從Object數組保留指定集合中的
     * 元素,爲false時從Object數組刪除指定集合中的元素
     */
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
        	/**
        	 * 遍歷Object數組,並檢查指定集合是否包含對應的元素,移動要保留的元素到
        	 * Object數組前面,w最終的值爲要保留的元素的數量
        	 * 簡單點兒說,要保留,就將相同的元素移動到Object數組前段;要刪除,就將不
        	 * 同的元素移動到Object數組的前段
        	 */
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            /**
             * finally塊確保異常拋出前,遍歷過的元素可以完成期望的操作,而未被遍歷的部分
             * 會被接到後面
        	 * r!=size時,表示可能出異常,c.contains(elementData[r])拋出的
        	 */
            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) {
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;//更新結構改變的次數
                size = w;//新的size爲保留的元素的個數
                modified = true;
            }
        }
        return modified;
    }

    /**
     * Save the state of the <tt>ArrayList</tt> instance to a stream (that
     * is, serialize it).
     *
     * @serialData The length of the array backing the <tt>ArrayList</tt>
     *             instance is emitted (int), followed by all of its elements
     *             (each an <tt>Object</tt>) in the proper order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;
        s.defaultWriteObject();

        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }

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

    /**
     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;

        // Read in size, and any hidden stuff
        s.defaultReadObject();

        // Read in capacity
        s.readInt(); // ignored

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

            Object[] a = elementData;
            // Read in all elements in the proper order.
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

    /**
     * 返回ArrayList對象的一個指定開始位置的迭代器
     */
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * 返回ArrayList對象的迭代器,從0開始
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 以適當的順序返回ArrayList對象的中
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * ArrayList普通的迭代器實現
     */
    private class Itr implements Iterator<E> {
        int cursor;       // 要返回的下一個元素的下標位置
        int lastRet = -1; // 要返回的最後一個元素的下標位置,沒有則返回-1
        int expectedModCount = modCount;//記錄當前集合機構改變的次數,用於防止迭代遍歷過程中改變集合

        public boolean hasNext() {
            return cursor != size;
        }
        
        //獲取當前迭代到的元素
        @SuppressWarnings("unchecked")
        public E next() {
        	/**
        	 * 判斷當前集合是否被改變,迭代過程中集合不可改變,否
        	 * 則拋ConcurrentModificationException異常
        	 */
            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();
            /**
        	 * 判斷當前集合是否被改變,迭代過程中集合不可改變,否
        	 * 則拋ConcurrentModificationException異常
        	 */
            checkForComodification();

            try {
            	/**
            	 * 在集合中移除當前元素,但不會影響到迭代器的迭代,remove會改變當前集合的modCount值
            	 */
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                /**
                 * 由於在這裏將當前集合的modCount賦予expectedModCount,因此checkForComodification
                 * 方法不會拋ConcurrentModificationException異常
                 */
                expectedModCount = modCount;
            } 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特有的迭代器實現
     */
    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() {
        	/**
        	 * 判斷當前集合是否被改變,迭代過程中集合不可改變,否
        	 * 則拋ConcurrentModificationException異常
        	 */
            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;
            return (E) elementData[lastRet = i];
        }

        /**
         * 使用新元素替換lastRet位置的舊元素,並返回舊元素
         */
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            /**
        	 * 判斷當前集合是否被改變,迭代過程中集合不可改變,否
        	 * 則拋ConcurrentModificationException異常
        	 */
            checkForComodification();

            try {
            	/**
            	 * ArrayList的set方法不會導致modCount發生改變,因此
            	 * 不會拋出ConcurrentModificationException異常
            	 */
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        /**
         * 將元素添加到cursor位置
         */
        public void add(E e) {
        	 /**
        	 * 判斷當前集合是否被改變,迭代過程中集合不可改變,否
        	 * 則拋ConcurrentModificationException異常
        	 */
            checkForComodification();

            try {
                int i = cursor;
                //調用ArrayList的add方法添加元素
                ArrayList.this.add(i, e);
                //下標後移一位
                cursor = i + 1;
                lastRet = -1;
                /**
                 * 由於在這裏將當前集合的modCount賦予expectedModCount,因此checkForComodification
                 * 方法不會拋ConcurrentModificationException異常
                 */
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * 以一個新的集合返回ArrayList對象[fromIndex,toIndex)範圍內的元素
     */
    public List<E> subList(int fromIndex, int toIndex) {
    	//檢查下標範圍是否合法
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > size)
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
    }

    /**
     * SubList的實現與ArrayList的類似,不多做說明
     * @author linxiaorui
     *
     */
    private class SubList extends AbstractList<E> implements RandomAccess {
        private final AbstractList<E> parent;
        private final int parentOffset;
        private final int offset;
        int size;

        SubList(AbstractList<E> parent,
                int offset, int fromIndex, int toIndex) {
            this.parent = parent;
            this.parentOffset = fromIndex;
            this.offset = offset + fromIndex;
            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;
        }

        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();
            E result = parent.remove(parentOffset + index);
            this.modCount = parent.modCount;
            this.size--;
            return result;
        }

        protected void removeRange(int fromIndex, int toIndex) {
            checkForComodification();
            parent.removeRange(parentOffset + fromIndex,
                               parentOffset + toIndex);
            this.modCount = parent.modCount;
            this.size -= toIndex - fromIndex;
        }

        public boolean addAll(Collection<? extends E> c) {
            return addAll(this.size, c);
        }

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

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

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

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

        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對象的一個可分割迭代器,下面會介紹
         */
        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++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
     * list.
     *
     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
     * Overriding implementations should document the reporting of additional
     * characteristic values.
     *
     * @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);
    }

    /** 基於下標位置的二分分割迭代器 */
    static final class ArrayListSpliterator<E> implements Spliterator<E> {

        /**
         *可分割迭代器,類比於我們常用的Iterator順序遍歷迭代器,Iterator是順序對元素進行遍歷的,
         *而可分割迭代器則可以進行並行的遍歷,在現在多核的時代,順序遍歷已無法滿足需求,因此爲發揮
         *多核的優勢,可以將集合的迭代器分割成多個部分,分配到不同的核上執行,於是就有了可分割迭代
         *器Spliterator,jdk1.8每一個集合都有其自己默認的Spliterator實現,ArrayList默認的
         *Spliterator實現就是基於"二分法"的Spliterator
         */

    	//用於存放ArrayList對象
        private final ArrayList<E> list;
        private int index; //起始位置(包含),執行advance或split操作時會改變
        private int fence; //結束位置(不包含),-1表示到最後一個元素
        private int expectedModCount; //用於存放ArrayList的modCount的值

        /** 創建一個覆蓋給定範圍的ArrayList可分割迭代器 */
        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
                             int expectedModCount) {
            this.list = list; 
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        /**
         * 獲取結束位置,首次初始化時需要對fence與expectedModCount進行賦值
         * @return
         */
        private int getFence() { 
            int hi; 
            ArrayList<E> lst;
            //只有當第一次進行初始化化時,fence纔會小於0
            if ((hi = fence) < 0) {
                if ((lst = list) == null)
                    hi = fence = 0;
                else {
                	//其他情況,fence就是集合元素的個數
                    expectedModCount = lst.modCount;
                    hi = fence = lst.size;
                }
            }
            return hi;
        }

        /**
         * 分割list,返回一個新分割出的spliterator實例,類似"二分法"
         */
        public ArrayListSpliterator<E> trySplit() {
            int hi = getFence(), //當前結束位置,"最高位"
            lo = index, //當前起始位置,"最低位"
            mid = (lo + hi) >>> 1;//計算"中間位置"
            return (lo >= mid) ? null ://當lo>=mid,表示不能在分割,返回null
            	////當lo<mid時,可分割,切割(lo,mid)出去,同時更新index=mid("二分法"也是這樣的吧)
                new ArrayListSpliterator<E>(list, lo, index = mid,expectedModCount);
        }

        //對單個元素執行給定的動作,如果有剩下元素未處理返回true,否則返回false
        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null)
                throw new NullPointerException();
            int hi = getFence(), i = index;
            //i<hi,起始位置<結束位置,自然表示還有一下個元素
            if (i < hi) {
                index = i + 1;//當前元素執行給定動作,起始位置index加1
                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
                action.accept(e);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        /**
         * 對每個剩餘元素執行給定的動作,依次處理,直到所有元素已被處理或被異常終
         * 止,Spliterator中默認是循環調用tryAdvance方法
         */
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi, mc; // hoist accesses and checks from loop
            ArrayList<E> lst; Object[] a;
            if (action == null)
                throw new NullPointerException();
            if ((lst = list) != null && (a = lst.elementData) != null) {
            	//表示第一次初始化,fence<0,應先進行初始化
                if ((hi = fence) < 0) {
                    mc = lst.modCount;
                    hi = lst.size;
                }
                else
                    mc = expectedModCount;
                if ((i = index) >= 0 && (index = hi) <= a.length) {
                    for (; i < hi; ++i) {
                        @SuppressWarnings("unchecked") E e = (E) a[i];
                        action.accept(e);
                    }
                    if (lst.modCount == mc)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

        //計算還剩下多少元素需要遍歷
        public long estimateSize() {
            return (long) (getFence() - index);
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }
}

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