ArrayList源碼分析

ArrayList源碼分析

一、Arraylist的實現繼承關係

Collection中有個iterator()方法,它的作用是返回一個Iterator接口,以便對集合內的元素進行遍歷操作。Collection分爲list可重複有序隊列集合和set不可重複集合,爲了方便抽象類AbstractCollection實現了其中的一部分方法。下面 
二、Iterable
public interface Iterable<T> {
    /**
     * 返回一個可以遍歷指定類型元素的迭代器
     */
    Iterator<T> iterator();

    /**
     * 此函數爲jdk1.8新特性,函數式編程,不是本文重點	
     */
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
    
    /**
     * 此函數爲jdk1.8新特性,函數式編程,不是本文重點	
     */
    default Spliterator<T> spliterator() {
        return Spliterators.spliteratorUnknownSize(iterator(), 0);
    }
}

三、Collection
public interface Collection<E> extends Iterable<E> {
    /**
     * 返回這個集合元素的長度,如果這個集合的長度超過整數的最大值,返回整數的最大值。
     */
    int size();

    /**
     * 如果這個集合爲空返回布爾值true。
     */
    boolean isEmpty();

    /**
     * 如果這個集合包含指定的元素就返回true
     */
    boolean contains(Object o);

    /**
     * 返回一個可以遍歷本集合指定類型元素的迭代器, 
     */
    Iterator<E> iterator();

    /**
     * 返回包含此 collection 中所有元素的數組
     */
    Object[] toArray();

    /**
     * 返回包含此 collection 中所有元素的數組;返回數組的運行時類型與指定數組的運行時類型相同。
     */
    <T> T[] toArray(T[] a);

    /**
     * 添加元素到集合
     */
    boolean add(E e);

    /**
     * 移除集合中指定的元素
     */
    boolean remove(Object o);

    /**
     * 如果此 collection 包含指定 collection 中的所有元素,則返回 true。
     */
    boolean containsAll(Collection<?> c);

    /**
     * 將指定 collection 中的所有元素都添加到此 collection 中
     */
    boolean addAll(Collection<? extends E> c);

    /**
     * 如果此 collection 包含指定 collection 中的所有元素,則返回 true。
     */
    boolean removeAll(Collection<?> c);

    /**
     * 此函數爲jdk1.8新特性,不是本文重點
     */
    default boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        boolean removed = false;
        final Iterator<E> each = iterator();
        while (each.hasNext()) {
            if (filter.test(each.next())) {
                each.remove();
                removed = true;
            }
        }
        return removed;
    }

    /**
     * 返回兩個集合的交集
     */
    boolean retainAll(Collection<?> c);

    /**
     * 清空集合
     */
    void clear();

    /**
     * 比較兩個集合是否相等,如果集合中指定元素不實現equals和hashCode方法,那麼兩個集合的值和地址相等才能爲true
     */
    boolean equals(Object o);

    /**
     * 返回此 collection 的哈希碼值。
     */
    int hashCode();

    /**
     * 此函數爲jdk1.8新特性,不是本文重點
     */
    @Override
    default Spliterator<E> spliterator() {
        return Spliterators.spliterator(this, 0);
    }

    /**
     * 此函數爲jdk1.8新特性,不是本文重點
     */
    default Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }

    /**
     *此函數爲jdk1.8新特性,不是本文重點
     */
    default Stream<E> parallelStream() {
        return StreamSupport.stream(spliterator(), true);
    }
}
Collection抽取了集合多需要的公共接口

四、AbstractCollection
public abstract class AbstractCollection<E> implements Collection<E> {
    protected AbstractCollection() {
    }

    /**
     * 返回在此 collection 中的元素上進行迭代的迭代器
     */
    public abstract Iterator<E> iterator();

    /**
     * 返回此 collection 中的元素數
     */
    public abstract int size();

    /**
     * 如果此 collection 不包含元素(爲空),則返回 true。
     */
    public boolean isEmpty() {
        return size() == 0;
    }

    /**
     * 如果這個集合包含指定的元素就返回true,(必須是值和地址相等,要麼實現equals和hashCode方法)
     */
    public boolean contains(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return true;
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return true;
        }
        return false;
    }

    /**
     * 返回包含此 collection 中所有元素的數組,因爲集合都有轉換成數組的方法,所以抽取到抽象類實現。
     */
    public Object[] toArray() {
        // 創建一個和集合大小一樣的數組
        Object[] r = new Object[size()];
        Iterator<E> it = iterator();
        for (int i = 0; i < r.length; i++) {
            if (! it.hasNext()) // 到集合結尾,而數組沒到結尾,拷貝一個新的數組,數組長度等於集合的長度
                return Arrays.copyOf(r, i);
            r[i] = it.next();
        }
        // 當集合元素超過數組的長度,也就是size()的時候,增加數組長度,保證所有集合元素轉換成數組元素。
        return it.hasNext() ? finishToArray(r, it) : r;
    }

    /**
     * 返回包含此 collection 中所有元素的數組;返回數組的運行時類型與指定數組的運行時類型相同。因爲集合都有轉換成數組的方法,所以抽取到抽象類實現。
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        // Estimate size of array; be prepared to see more or fewer elements
        int size = size();
        // 如果參數數組的長度比返回方法size()長度還小,因爲是泛型需要通過反射來創建一個類型一樣的數組
        T[] r = a.length >= size ? a :
                  (T[])java.lang.reflect.Array
                  .newInstance(a.getClass().getComponentType(), size);
        Iterator<E> it = iterator();

        for (int i = 0; i < r.length; i++) {
            if (! it.hasNext()) { // fewer elements than expected
                if (a == r) { // 數組的長度等於集合的長度
                    r[i] = null; // null-terminate
                } else if (a.length < i) { // 數組的長度比集合長度小,複製一個新的數組
                    return Arrays.copyOf(r, i);
                } else { // 集合長度出現異常,將r數組內容複製到a數組中。
                    System.arraycopy(r, 0, a, 0, i);
                    if (a.length > i) {
                        a[i] = null;
                    }
                }
                return a;
            }
            r[i] = (T)it.next();
        }
         // 當集合元素超過數組的長度,也就是size()的時候,增加數組長度,保證所有集合元素轉換成數組元素。
        return it.hasNext() ? finishToArray(r, it) : r;
    }

    /**
     * 數組需要設置的最大長度,不能超過jvm虛擬機的限制的長度
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 當集合元素超過數組的長度,也就是size()的時候,增加數組長度,保證所有集合元素轉換成數組元素。
     */
    @SuppressWarnings("unchecked")
    private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
        int i = r.length;
        while (it.hasNext()) {
            int cap = r.length;
            // 如果是第一次執行,爲數組增加1.5倍+1的長度
            if (i == cap) { 
                int newCap = cap + (cap >> 1) + 1;
                // 溢出檢測代碼
                if (newCap - MAX_ARRAY_SIZE > 0)
                    newCap = hugeCapacity(cap + 1);
                r = Arrays.copyOf(r, newCap);
            }
            r[i++] = (T)it.next();
        }
        // 如果超過集合大小,對數組進行剪裁
        return (i == r.length) ? r : Arrays.copyOf(r, i);
    }

    /**
     * 確定數組是否超過數組的最大值,也就是整形的最大值2^31-1-8,如果爲負數,表示內存錯誤。
     * @param  minCapacity [description]
     * @return             [description]
     */
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) 
            throw new OutOfMemoryError
                ("Required array size too large");
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    // Modification Operations

    /**
     * 添加元素到集合中,具體集合必須要重寫這個類,否則調用拋出UnsupportedOperationException異常。
     */
    public boolean add(E e) {
        throw new UnsupportedOperationException();
    }

    /**
     * 移除指定的集合元素
     */
    public boolean remove(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext()) {
                if (it.next()==null) {
                    it.remove();
                    return true;
                }
            }
        } else {
            while (it.hasNext()) {
                if (o.equals(it.next())) {
                    it.remove();
                    return true;
                }
            }
        }
        return false;
    }


    // Bulk Operations

    /**
     *  如果此 collection 包含指定 collection 中的所有元素,則返回 true。
     */
    public boolean containsAll(Collection<?> c) {
        for (Object e : c)
            if (!contains(e))
                return false;
        return true;
    }

    /**
     * 將指定 collection 中的所有元素都添加到此 collection 中
     */
    public boolean addAll(Collection<? extends E> c) {
        boolean modified = false;
        for (E e : c)
            if (add(e))
                modified = true;
        return modified;
    }

    /**
     * 移除此 collection 中那些也包含在指定 collection 中的所有元素
     */
    public boolean removeAll(Collection<?> c) {
        // 如果集合c爲null,那麼拋空指針異常,不執行後面的代碼,從jdk1.7開始
        Objects.requireNonNull(c);
        boolean modified = false;
        Iterator<?> it = iterator();
        while (it.hasNext()) {
            if (c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

    /**
     * 取兩個集合的交集
     */
    public boolean retainAll(Collection<?> c) {
        // 如果集合c爲null,那麼拋空指針異常,不執行後面的代碼,從jdk1.7開始
        Objects.requireNonNull(c);
        boolean modified = false;
        Iterator<E> it = iterator();
        while (it.hasNext()) {
            if (!c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

    /**
     * 移除此 collection 中的所有元素
     */
    public void clear() {
        Iterator<E> it = iterator();
        while (it.hasNext()) {
            it.next();
            it.remove();
        }
    }


    //  String conversion

    /**
     * 返回此 collection 的字符串表示形式。
     */
    public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }

}
AbstractCollection實現了集合所需要的公共方法

五、List
public interface List<E> extends Collection<E> {
    /**
     * 返回此 collection 中的元素數
     */
    int size();

    /**
     * 如果此 collection 不包含元素(爲空),則返回 true。
     */
    boolean isEmpty();

    /**
     * 如果這個集合包含指定的元素就返回true,(必須是值和地址相等,要麼實現equals和hashCode方法)
     */
    boolean contains(Object o);

    /**
     * 返回在此 collection 中的元素上進行迭代的迭代器
     */
    Iterator<E> iterator();

     /**
     * 返回包含此 collection 中所有元素的數組,因爲集合都有轉換成數組的方法,所以抽取到抽象類實現。
     */
    Object[] toArray();

     /**
     * 返回包含此 collection 中所有元素的數組;返回數組的運行時類型與指定數組的運行時類型相同。因爲集合都有轉換成數組的方法,所以抽取到抽象類實現。
     */
    <T> T[] toArray(T[] a);

   /**
     * 添加元素到集合中,具體集合必須要重寫這個類,否則調用拋出UnsupportedOperationException異常。
     */
    boolean add(E e);

    /**
     * 移除指定的集合元素
     */
    boolean remove(Object o);

    /**
     *  如果此 collection 包含指定 collection 中的所有元素,則返回 true。
     */
    boolean containsAll(Collection<?> c);

    /**
     * 將指定 collection 中的所有元素都添加到此 collection 中
     */
    boolean addAll(Collection<? extends E> c);

    /**
     * 將指定 collection 中的所有元素都插入到列表中的指定位置
     */
    boolean addAll(int index, Collection<? extends E> c);

    /**
     * 移除此 collection 中那些也包含在指定 collection 中的所有元素
     */
    boolean removeAll(Collection<?> c);

    /**
     * 取兩個集合的交集
     */
    boolean retainAll(Collection<?> c);

    /**
     * jdk1.8新特性
     */
    default void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final ListIterator<E> li = this.listIterator();
        while (li.hasNext()) {
            li.set(operator.apply(li.next()));
        }
    }

    /**
     * jdk1.8 新特性,對集合進行排序
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }

    /**
     * 移除此 collection 中的所有元素
     */
    void clear();

    /** 
     * 比較指定的對象與列表是否相等。如果集合內對象不實現equals和hashCode,那麼equals和==一樣,地址和值都相等才能爲true
     */
    boolean equals(Object o);

    /**
     *  返回列表的哈希碼值。
     */
    int hashCode();

    /**
     * 返回列表中指定位置的元素。
     */
    E get(int index);

    /**
     *  用指定元素替換列表中指定位置的元素(可選操作)。
     */
    E set(int index, E element);

    /**
     * 在列表的指定位置插入指定元素
     */
    void add(int index, E element);

    /**
     * 移除列表中指定位置的元素
     */
    E remove(int index);


    // Search Operations

    /**
     * 返回此列表中第一次出現的指定元素的索引;如果此列表不包含該元素,則返回 -1。
     */
    int indexOf(Object o);

    /**
     * 返回此列表中最後出現的指定元素的索引;如果列表不包含此元素,則返回 -1。
     */
    int lastIndexOf(Object o);

    /**
     * 返回此列表元素的列表迭代器
     */
    ListIterator<E> listIterator();

    /**
     *返回列表中元素的列表迭代器(按適當順序),從列表的指定位置開始。
     */
    ListIterator<E> listIterator(int index);

    /**
     * 返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之間的部分視圖。
     */
    List<E> subList(int fromIndex, int toIndex);

    /**
     * jdk1.8 新特性
     */
    @Override
    default Spliterator<E> spliterator() {
        return Spliterators.spliterator(this, Spliterator.ORDERED);
    }
}
實現了list集合類大部分接口
六、AbstractList
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    /**
     * Sole constructor.  (For invocation by subclass constructors, typically
     * implicit.)
     */
    protected AbstractList() {
    }

    /**
     * 向列表的尾部添加指定的元素
     */
    public boolean add(E e) {
        add(size(), e);
        return true;
    }

    /**
     * 返回列表中指定位置的元素
     */
    abstract public E get(int index);

    /**
     * 用指定元素替換列表中指定位置的元素,子類必須要實現這個類,否則調用拋UnsupportedOperationException異常
     */
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }

    /**
     * 添加元素到列表中指定位置,子類必須要實現這個類,否則調用拋UnsupportedOperationException異常
     */
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

    /**
     * 移除列表中指定位置的元素,子類必須要實現這個類,否則調用拋UnsupportedOperationException異常
     */
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }

    /**
     * 返回此列表中第一次出現的指定元素的索引;如果此列表不包含該元素,則返回 -1。
     */
    public int indexOf(Object o) {
        // 獲取list所獨有的迭代器
        ListIterator<E> it = listIterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return it.previousIndex();
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return it.previousIndex();
        }
        return -1;
    }

    /**
     * 返回此列表中最後一次出現的指定元素的索引;如果此列表不包含該元素,則返回 -1。
     */
    public int lastIndexOf(Object o) {
        // 獲取list所獨有的迭代器
        ListIterator<E> it = listIterator(size());
        if (o==null) {
            while (it.hasPrevious())
                if (it.previous()==null)
                    return it.nextIndex();
        } else {
            while (it.hasPrevious())
                if (o.equals(it.previous()))
                    return it.nextIndex();
        }
        return -1;
    }

    /**
     * 移除此 collection 中的所有元素
     */
    public void clear() {
        // 移除指定範圍內的元素
        removeRange(0, size());
    }

    /**
     * 將指定 collection 中的所有元素都插入到列表中的指定位置
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        // 檢查索引是否超過列表索引的範圍
        rangeCheckForAdd(index);
        boolean modified = false;
        for (E e : c) {
            add(index++, e);
            modified = true;
        }
        return modified;
    }

    /**
     * 返回迭代器
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * 返回此列表元素的列表迭代器
     */
    public ListIterator<E> listIterator() {
        return listIterator(0);
    }

    /**
     * 返回列表中元素的列表迭代器(按適當順序),從列表的指定位置開始。
     */
    public ListIterator<E> listIterator(final int index) {
        // 檢查索引是否超過列表索引的範圍
        rangeCheckForAdd(index);

        return new ListItr(index);
    }

    /**
     * 實現迭代器
     */
    private class Itr implements Iterator<E> {
        /**
         * 集合當前元素的索引
         */
        int cursor = 0;

        /**
         * 返回集合上一個迭代元素的索引,如果刪除那麼值設置爲-1
         */
        int lastRet = -1;

        /**
         * 如果這個值發生了改變,說明集合出現了併發問題
         */
        int expectedModCount = modCount;

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

        /**
         * 獲取下一個元素
         */
        public E next() {
            // 檢查是否出現併發問題
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        /**
         * 刪除當前元素
         */
        public void remove() {
            // 如果lastRet爲-1,也就是當前元素已經被刪除。
            if (lastRet < 0)
                throw new IllegalStateException();
            // 檢查是否出現併發問題
            checkForComodification();

            try {
                // 調用外部類的刪除元素的方法
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }

        /**
         * 判斷是否出現了併發問題
         */
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            cursor = index;
        }

        /**
         * 判斷是否有當前元素
         */
        public boolean hasPrevious() {
            return cursor != 0;
        }

        /**
         * 獲取當前元素
         */
        public E previous() {
            // 檢查是否有併發問題
            checkForComodification();
            try {
                int i = cursor - 1;
                E previous = get(i);
                lastRet = cursor = i;
                return previous;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        /**
         * 獲取下一個元素的索引
         */
        public int nextIndex() {
            return cursor;
        }

        /**
         * 獲取當前元素的索引
         */
        public int previousIndex() {
            return cursor-1;
        }

        /**
         * 改變當前元素的值
         */
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            // 檢查是否有併發問題
            checkForComodification();

            try {
                // 調用外部類設置元素的值,索引爲當前元素的索引
                AbstractList.this.set(lastRet, e);
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        public void add(E e) {
            // 檢查是否有併發問題
            checkForComodification();

            try {
                int i = cursor;
                // 調用外部類添加元素到下一個元素的前面.
                AbstractList.this.add(i, e);
                lastRet = -1;
                cursor = i + 1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * 返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之間的部分視圖。
     */
    public List<E> subList(int fromIndex, int toIndex) {
        return (this instanceof RandomAccess ?
                new RandomAccessSubList<>(this, fromIndex, toIndex) :
                new SubList<>(this, fromIndex, toIndex));
    }

    /**
     * 比較指定的對象與列表是否相等。如果集合內對象不實現equals和hashCode,那麼equals和==一樣,地址和值都相等才能爲true
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;
        // 判斷元素的類型爲list
        if (!(o instanceof List))
            return false;

        ListIterator<E> e1 = listIterator();
        ListIterator<?> e2 = ((List<?>) o).listIterator();
        while (e1.hasNext() && e2.hasNext()) {
            E o1 = e1.next();
            Object o2 = e2.next();
            if (!(o1==null ? o2==null : o1.equals(o2)))
                return false;
        }
        return !(e1.hasNext() || e2.hasNext());
    }

    /**
     * 返回列表的哈希碼值。
     */
    public int hashCode() {
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    }

    /**
     * 刪除指定範圍內的元素
     */
    protected void removeRange(int fromIndex, int toIndex) {
        ListIterator<E> it = listIterator(fromIndex);
        for (int i=0, n=toIndex-fromIndex; i<n; i++) {
            it.next();
            it.remove();
        }
    }

    /**
     * list集合被修改的次數
     */
    protected transient int modCount = 0;

    /**
     * 檢查索引是否在集合索引範圍內
     * @param index [description]
     */
    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size())
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size();
    }
}
/**
 * 切割集合類的實現
 */
class SubList<E> extends AbstractList<E> {
    private final AbstractList<E> l;
    private final int offset;
    private int size;

    SubList(AbstractList<E> list, int fromIndex, int toIndex) {
        // 索引範圍檢查
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > list.size())
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");

        // 初始化
        l = list;
        offset = fromIndex;
        size = toIndex - fromIndex;
        this.modCount = l.modCount;
    }

    /**
     * 修改指定位置的元素
     */
    public E set(int index, E element) {
        // 檢查索引範圍,不包含最後一個索引位置
        rangeCheck(index);
        // 檢查是否出現了併發問題
        checkForComodification();
        return l.set(index+offset, element);
    }

    /**
     * 獲取指定位置的元素
     */
    public E get(int index) {
        // 檢查索引範圍,不包含最後一個索引位置
        rangeCheck(index);
        // 檢查是否出現了併發問題
        checkForComodification();
        return l.get(index+offset);
    }

    /**
     * 獲取集合的元素的個數
     */
    public int size() {
        // 檢查是否有併發問題
        checkForComodification();
        return size;
    }

    /**
     * 添加元素到指定位置
     */
    public void add(int index, E element) {
        // 檢查添加索引的範圍
        rangeCheckForAdd(index);
        // 檢查是否有併發問題
        checkForComodification();
        l.add(index+offset, element);
        this.modCount = l.modCount;
        size++;
    }

    /**
     * 移除指定位置的元素
     */
    public E remove(int index) {
        // 檢查索引範圍,不包含最後一個索引位置
        rangeCheck(index);
        // 檢查是否有併發問題
        checkForComodification();
        E result = l.remove(index+offset);
        this.modCount = l.modCount;
        size--;
        return result;
    }

    /**
     * 移除指定範圍內的元素
     */
    protected void removeRange(int fromIndex, int toIndex) {
        // 檢查是否有併發問題
        checkForComodification();
        l.removeRange(fromIndex+offset, toIndex+offset);
        this.modCount = l.modCount;
        size -= (toIndex-fromIndex);
    }

    /**
     * 添加集合到指定集合的最後
     */
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    /**
     * 添加集合到指定集合的指定位置
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        // 檢查索引範圍
        rangeCheckForAdd(index);
        // 如果集合內沒有元素,不允許添加
        int cSize = c.size();
        if (cSize==0)
            return false;
        // 檢查併發問題
        checkForComodification();
        l.addAll(offset+index, c);
        this.modCount = l.modCount;
        size += cSize;
        return true;
    }

    /**
     * 獲取list迭代器
     */
    public Iterator<E> iterator() {
        return listIterator();
    }

    public ListIterator<E> listIterator(final int index) {
        // 檢查是否有併發問題
        checkForComodification();
        // 檢查索引範圍
        rangeCheckForAdd(index);

        return new ListIterator<E>() {
            private final ListIterator<E> i = l.listIterator(index+offset);

            /**
             * 判斷是否有下一個元素
             */
            public boolean hasNext() {
                return nextIndex() < size;
            }

            /**
             * 獲取下一個元素
             */
            public E next() {
                if (hasNext())
                    return i.next();
                else
                    throw new NoSuchElementException();
            }

            /**
             * 判斷是否有當前元素
             */
            public boolean hasPrevious() {
                return previousIndex() >= 0;
            }

            /**
             * 獲取當前元素
             */
            public E previous() {
                if (hasPrevious())
                    return i.previous();
                else
                    throw new NoSuchElementException();
            }

            /**
             * 獲取下一個元素的索引
             */
            public int nextIndex() {
                return i.nextIndex() - offset;
            }

            /**
             * 獲取當前元素的索引
             */
            public int previousIndex() {
                return i.previousIndex() - offset;
            }

            /**
             * 刪除當前元素
             */
            public void remove() {
                i.remove();
                SubList.this.modCount = l.modCount;
                size--;
            }

            /**
             * 修改當前元素
             */
            public void set(E e) {
                i.set(e);
            }

            /**
             * 添加元素的集合尾部
             */
            public void add(E e) {
                i.add(e);
                SubList.this.modCount = l.modCount;
                size++;
            }
        };
    }

    public List<E> subList(int fromIndex, int toIndex) {
        return new SubList<>(this, fromIndex, toIndex);
    }

    /**
     * 檢查索引的範圍,不包括最後一個位置
     * @param index [description]
     */
    private void rangeCheck(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 檢查索引的範圍
     * @param index [description]
     */
    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

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

    /**
     * 檢查是否有併發問題
     */
    private void checkForComodification() {
        if (this.modCount != l.modCount)
            throw new ConcurrentModificationException();
    }
}

class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
    RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
        super(list, fromIndex, toIndex);
    }

    public List<E> subList(int fromIndex, int toIndex) {
        return new RandomAccessSubList<>(this, fromIndex, toIndex);
    }
}

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

    /**
     * 定義初始化的容量,如果元素小於默認長度,都採用默認長度
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 共享的空數組實體
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 共享的空數組實體,如果構造器沒有指定長度,採用這個空數組。
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 存放arraylist集合的元素的數組
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * arraylist集合的長度
     */
    private int size;

    /**
     * 初始化一個有指定長度的數組
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) { // 如果指定容量大於0
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) { // 如果指定容量小於0,則使用默認長度10
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * 初始化一個長度爲默認10的數組
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 將一個colection指定集合轉換成arraylist集合
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray 可能不會返回一個數組,只有返回數組才進行轉換
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 使用空數組
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * 將此 ArrayList 實例的容量調整爲列表的當前大小。
     */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 如有必要,增加此 ArrayList 實例的容量,以確保它至少能夠容納最小容量參數所指定的元素數。
     */
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // any size if not default element table
            ? 0
            // larger than default for default empty table. It's already
            // supposed to be at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    /**
     * 增加此 ArrayList 實例的容量,以確保它至少能夠容納最小容量參數所指定的元素數。確定構造器是無參數的。
     */
    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);
    }

    /**
     * 數組需要設置的最大長度,不能超過jvm虛擬機的限制的長度 
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 保證容納最小容量參數所指定的元素數的實現,如果指定長度比實際數組的容量1.5倍還要大,那麼採用指定長度,否則容量爲原來的1.5倍
     */
    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);
    }

    /**
     * 確定數組的最大容量
     */
    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;
    }

    /**
     * 如果此列表中沒有元素,則返回 true
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 如果此列表中包含指定的元素,則返回 true。
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * 返回此列表中首次出現的指定元素的索引,或如果此列表不包含元素,則返回 -1。
     */
    public int indexOf(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;
    }

    /**
     * 返回此列表中最後一次出現的指定元素的索引,或如果此列表不包含元素,則返回 -1。
     */
    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;
    }

    /**
     * 返回此 ArrayList 實例的淺表副本
     */
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    /**
     * 按適當順序(從第一個到最後一個元素)返回包含此列表中所有元素的數組。
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * 按適當順序(從第一個到最後一個元素)返回包含此列表中所有元素的數組;返回數組的運行時類型是指定數組的運行時類型。
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

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

    /**
     * 返回指定位置的元素
     */
    public E get(int index) {
        // 索引越界檢查
        rangeCheck(index);

        return elementData(index);
    }

    /**
     * 用指定的元素替代此列表中指定位置上的元素。
     */
    public E set(int index, E element) {
        // 索引越界檢查
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    /**
     * 將指定的元素添加到此列表的尾部。
     */
    public boolean add(E e) {
        // 確定數組的最小容量,爲數組實際長度的1.5倍
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    /**
     * 將指定的元素插入此列表中的指定位置。
     */
    public void add(int index, E element) { 
        // 確定增加元素的索引是否越界
        rangeCheckForAdd(index);
        // 確定數組的最小容量,爲數組實際長度的1.5倍
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

    /**
     * 移除指定位置的元素
     */
    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
    }

    /**
     * 清楚所有的元素
     */
    public void clear() {
        modCount++;

        // 讓垃圾回收機制進行回收
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

    /**
     * 按照指定 collection 的迭代器所返回的元素順序,將該 collection 中的所有元素添加到此列表的尾部。
     */
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        // 確定數組的最小容量,爲數組實際長度的1.5倍
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

    /**
     * 從指定的位置開始,將指定 collection 中的所有元素插入到此列表中。
     */
    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;
    }

    /**
     * 移除指定範圍內的元素
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // 讓垃圾回收機制進行回收
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        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));
    }

    /**
     * Constructs an IndexOutOfBoundsException detail message.
     * Of the many possible refactorings of the error handling code,
     * this "outlining" performs best with both server and client VMs.
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /**
     * 移除本集合內指定的子集合
     */
    public boolean removeAll(Collection<?> c) {
        // 如果集合c爲null,那麼拋空指針異常,不執行後面的代碼,從jdk1.7開始 
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    /**
     * 取兩個集合的交集
     */
    public boolean retainAll(Collection<?> c) {
        // 如果集合c爲null,那麼拋空指針異常,不執行後面的代碼,從jdk1.7開始 
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            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;
    }

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

    /**
     * 根據索引獲取list迭代器
     */
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * 獲取list迭代器,從開始位置
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 獲取迭代器
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * 獲取list迭代器
     */
    private class Itr implements Iterator<E> {
        // 集合當前元素的索引
        int cursor;  
        // 返回集合上一個迭代元素的索引,如果刪除那麼值設置爲-1 
        int lastRet = -1; 
        // 如果這個值發生了改變,說明集合出現了併發問題 
        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();
            }
        }

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

    /**
     * An optimized version of AbstractList.ListItr
     */
    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

        /** 
         * 判斷是否有當前元素 
         */  
        public boolean hasPrevious() {
            return cursor != 0;
        }

        /** 
         * 獲取下一個元素的索引 
         */
        public int nextIndex() {
            return cursor;
        }

        /**
         * 獲取當前元素的索引
         */
        public int previousIndex() {
            return cursor - 1;
        }

        /** 
         * 獲取當前元素 
         */ 
        @SuppressWarnings("unchecked")
        public E previous() {
            // 檢查是否有併發問題 
            checkForComodification();
            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];
        }

        /** 
         * 改變當前元素的值 
         */
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            // 檢查是否有併發問題 
            checkForComodification();

            try {
                // 調用外部類設置元素的值,索引爲當前元素的索引  
                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);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /** 
     * 返回列表中指定的 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 + ")");
    }

    /** 
     * 切割集合類的實現 
     */ 
    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;
        }

        /** 
         * 獲取list迭代器 
         */
        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();
        }

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

    /** Index-based split-by-two, lazily initialized Spliterator */
    static final class ArrayListSpliterator<E> implements Spliterator<E> {

        /*
         * If ArrayLists were immutable, or structurally immutable (no
         * adds, removes, etc), we could implement their spliterators
         * with Arrays.spliterator. Instead we detect as much
         * interference during traversal as practical without
         * sacrificing much performance. We rely primarily on
         * modCounts. These are not guaranteed to detect concurrency
         * violations, and are sometimes overly conservative about
         * within-thread interference, but detect enough problems to
         * be worthwhile in practice. To carry this out, we (1) lazily
         * initialize fence and expectedModCount until the latest
         * point that we need to commit to the state we are checking
         * against; thus improving precision.  (This doesn't apply to
         * SubLists, that create spliterators with current non-lazy
         * values).  (2) We perform only a single
         * ConcurrentModificationException check at the end of forEach
         * (the most performance-sensitive method). When using forEach
         * (as opposed to iterators), we can normally only detect
         * interference after actions, not before. Further
         * CME-triggering checks apply to all other possible
         * violations of assumptions for example null or too-small
         * elementData array given its size(), that could only have
         * occurred due to interference.  This allows the inner loop
         * of forEach to run without any further checks, and
         * simplifies lambda-resolution. While this does entail a
         * number of checks, note that in the common case of
         * list.stream().forEach(a), no checks or other computation
         * occur anywhere other than inside forEach itself.  The other
         * less-often-used methods cannot take advantage of most of
         * these streamlinings.
         */

        private final ArrayList<E> list;
        private int index; // current index, modified on advance/split
        private int fence; // -1 until used; then one past last index
        private int expectedModCount; // initialized when fence set

        /** Create new spliterator covering the given  range */
        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;
        }

        private int getFence() { // initialize fence to size on first use
            int hi; // (a specialized variant appears in method forEach)
            ArrayList<E> lst;
            if ((hi = fence) < 0) {
                if ((lst = list) == null)
                    hi = fence = 0;
                else {
                    expectedModCount = lst.modCount;
                    hi = fence = lst.size;
                }
            }
            return hi;
        }

        public ArrayListSpliterator<E> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null : // divide range in half unless too small
                new ArrayListSpliterator<E>(list, lo, index = mid,
                                            expectedModCount);
        }

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

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

    @Override
    public boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // figure out which elements are to be removed
        // any exception thrown from the filter predicate at this stage
        // will leave the collection unmodified
        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);
                removeCount++;
            }
        }
        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);
                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;
    }

    @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++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

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





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