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





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值