ArrayList源码解析

package java.util;             //util包

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import sun.misc.SharedSecrets;

//继承AbstractList抽象类
//实现List接口;实现RandomAccess接口,做到随机访问,实现Cloneable接口,克隆;实现Serializable接口,序列化(不需要真正实现,只要这样类似声明一下,就知道这个类可以序列化了)
public class ArrayList<E> extends AbstractList<E>         
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable    
{
    private static final long serialVersionUID = 8683452581122892189L;    //UID:版本号,序列化和反序列化时候用来对照的

    
    private static final int DEFAULT_CAPACITY = 10;    //ArrayList初始容量为10,也可以自己设置

    private static final Object[] EMPTY_ELEMENTDATA = {};    //EMPTY_ELEMENTDATA是一个Object的数组,该数组为空;用final修饰,引用无法指向其它对象;static修饰,类加载时就会创建

    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};    //空的数组,为了和上述区别,因为这是默认初始化时分配的数组

    
    transient Object[] elementData; // 存放数据的Object数组,transient修饰表示不参与序列化

    private int size;    //数组存放东西的长度

    public ArrayList(int initialCapacity) {    //第一个带参构造方法,参数是ArrayList数组的大小
        if (initialCapacity > 0) {    //当传入的参数大于0时(正确)
            this.elementData = new Object[initialCapacity];    //新建一个对象数组,并将其赋值给elementData
        } else if (initialCapacity == 0) {    //当传入的参数等于0时,将一开始创建的EMPTY_ELEMENTDATA数组赋值给elementData
            this.elementData = EMPTY_ELEMENTDATA;
        } else {    //当传入的参数小于0时(不合法),抛出参数错误异常
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    public ArrayList() {    //默认构造方法,初始为空,DEFAULTCAPACITY_EMPTY_ELEMENTDATA
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;    //DEFAULTCAPACITY_EMPTY_ELEMENTDATA赋值给elementData
    }

    public ArrayList(Collection<? extends E> c) {    第三个构造方法,参数是一个Collection,Collection中存放的是E(ArrayList中的元素)或者E的子类
        elementData = c.toArray();    //将Collection装换为array,也就是一个数组;
        if ((size = elementData.length) != 0) {    //如果elementData的长度不为0
            // c.toArray might (incorrectly) not return Object[] (see 6260652) ,6260652是jdk bug库中的编号
            if (elementData.getClass() != Object[].class)    //如果转为Array之后不是Object数组,则要利用Arrays.copyOf转化为Object数组
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {    //如果elementData的长度为0,将其转化为EMPTY_ELEMENTDATA
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    public void trimToSize() {    //截短ArrayList,可能elementData.length > size,那么就可以保留数据部分,将之后的去除,注意,modCount会增加。
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

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

    private static int calculateCapacity(Object[] elementData, int minCapacity) {    //计算容量  
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {    //如果数组为空,那么返回初始大小和minCapacity的最大值,也就是说最小为10
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;    //如果数组不为空,那么返回minCapacity
    }

    private void ensureCapacityInternal(int minCapacity) {    //确保数组的大小大于等于minCapacity,这里的minCapcity其实就是数组最后要多大
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    private void ensureExplicitCapacity(int minCapacity) {    //如果minCapacity大于数组的长度,就会执行grow函数增长,并且modCount也会增加,modCount是AbstractList中的成员,标识版本
        modCount++;

        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;    //最大的长度0x7fffffff - 8

    private void grow(int minCapacity) {    //扩容操作,
        // overflow-conscious code
        int oldCapacity = elementData.length;    //记录原数组的长度(不是size)
        int newCapacity = oldCapacity + (oldCapacity >> 1);    //新数组的长度为原数组长度的1.5倍
        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    //如果最小长度小于0,那么判定为溢出,抛出异常
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?    //如果最小长度大于最大容量,返回整数的最大值,否则返回最大容量
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    public int size() {    //返回list的元素个数
        return size;
    }

    public boolean isEmpty() {    //判断list中是否存在元素
        return size == 0;
    }

    public boolean contains(Object o) {    //判断list中是否存在某个对象
        return indexOf(o) >= 0;
    }

    public int indexOf(Object o) {    //返回某个对象在list中的位置,也就是下标
        if (o == null) {    //如果对象为空,那么找到list中第一个为空的元素,返回其下标
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {    //如果对象不为空,那么找到list中第一个等于该对象的元素,返回其下标,这里看似差不多的逻辑,但是不能一起做,因为如果传入的对象为空,会报空指针NullPointerException
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;    //如果没找到,那么返回-1,让调用者知道没有
    }

    public int lastIndexOf(Object o) {    //同样寻找某个对象的下标,和indexOf()的区别在于,list中可能有几个同样的该对象,indexOf是从前往后找,并返回第一个,而lastIndexOf()是从后往前找,返回最后一个
        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;
    }

    public Object clone() {    //重写了clone()方法,因为调用Object的clone()方法需要实现Cloneable接口,该接口没有任何方法,和Serialization一样,只是标志。并且Object的clone()是protected修饰的,意味着不重写的话其它类可能用不了这个方法
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();    //调用clone()方法,并且强转为ArrayList类型,用v接收,v为复制的数组
            v.elementData = Arrays.copyOf(elementData, size);    //复制原数组中的元素,因为Object的clone()是浅复制,如果存放的是对象的话,这里原数组和复制的数组放的东西都是一样的
            v.modCount = 0;    //初始化复制的数组的modCount = 0
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    public Object[] toArray() {    //利用Arrays.copyOf()返回一个数组
        return Arrays.copyOf(elementData, size);
    }

    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {    //将ArrayList转化为特定的数组,而不一定是Object数组
        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;    //如果传入的数组长度太大,那么需要将size位置为null,以求得数组的size(只有数组中不存在其它null元素的时候管用)
        return a;
    }

    @SuppressWarnings("unchecked")       //返回ArrayList特定下标的元素
    E elementData(int index) {
        return (E) elementData[index];
    }

    public E get(int index) {    //得到ArrayList特定下标的元素,根本上调用了elementData()函数
        rangeCheck(index);    //判断index的合法性

        return elementData(index);
    }

    public E set(int index, E element) {    //设置下标为index的元素,并且该元素为泛型元素,需要和初始设定相同
        rangeCheck(index);    //检查index的合法性

        E oldValue = elementData(index);    //保存数组中index上原来的元素
        elementData[index] = element;    //设置新的值
        return oldValue;    //返回原来的元素
    }

    //add()方法要注意的是,其实初始的ArrayList的大小为0,如果增加一个元素,那么就会增长到默认大小,也就是10,这是jdk1.8的修改
    public boolean add(E e) {    //添加一个元素,modCount + 1
        ensureCapacityInternal(size + 1);  // 确保数组大小足够,其中会执行ensureExplicitCapacity()方法,该方法会增加modCount
        elementData[size++] = e;    //size之后的空格内存放该元素
        return true;    //返回true,代表添加正确
    }


    public void add(int index, E element) {    //往特定的index上增加一个元素,modCount + 1
        rangeCheckForAdd(index);    //检查index的合法性

        ensureCapacityInternal(size + 1);  // 确保数组大小足够,其中会执行ensureExplicitCapacity()方法,该方法会增加modCount
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);    //将index及其之后的元素往后移动,腾出位子
        elementData[index] = element;    //放入该元素
        size++;    //修改size
    }

    public E remove(int index) {    //删除某个index上的元素,modCount + 1
        rangeCheck(index);    //检查index的合法性

        modCount++;    //modCount + 1(删除不需要检查容量问题)
        E oldValue = elementData(index);    //保存index上的元素

        int numMoved = size - index - 1;    //计算需要移动的元素个数
        if (numMoved > 0)    //如果要移动的元素个数大于0,也就是说index不是最后一个
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);    //移动数组,将后面的往前移动
        elementData[--size] = null;     // 将最后一个置为空,以待回收

        return oldValue;    //返回删除的那个元素
    }

    public boolean remove(Object o) {    //删除某个对象,会调用fastRemove(),增加modCount
        if (o == null) {    //如果该对象为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++,和普通删除一个元素的区别在于不返回删除的元素,并且这个方法是私有方法
        modCount++;    //增加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++
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)    //将数组上size以内的元素都置为null
            elementData[i] = null;

        size = 0;    //更新size
    }

    public boolean addAll(Collection<? extends E> c) {    //增加一个集合中的所有元素,modCount++
        Object[] a = c.toArray();    //首先将集合c转化为数组a
        int numNew = a.length;    //计算数组a的长度
        ensureCapacityInternal(size + numNew);  // 确保ArrayList的长度够,这里会调用ensureExplicitCapacity(),所以modCount++
        System.arraycopy(a, 0, elementData, size, numNew);    //将a数组复制到ArrayList的size之后
        size += numNew;    //更新size
        return numNew != 0;    //如果a数组的长度为0,返回false,否则返回true
    }

    public boolean addAll(int index, Collection<? extends E> c) {    //将集合c中的元素都插入index之后,和上一个方法的区别在于插入的位置,以及要使用两次System.arraycopy()方法
        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);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

    private void rangeCheck(int index) {    //私有方法,index检查
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private void rangeCheckForAdd(int index) {    //私有方法,index检查,和上一个方法的区别在于多用于add之类的方法中,所以index可以等于size(可以在size位子上增加),index < 0
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private String outOfBoundsMsg(int index) {    //返回一个outOfBounds信息
        return "Index: "+index+", Size: "+size;
    }

    public boolean removeAll(Collection<?> c) {    //删除集合中的所有元素
        Objects.requireNonNull(c);    //c不能是空
        return batchRemove(c, false);    //调用batchRemove(),
    }

    public boolean retainAll(Collection<?> c) {    //保留集合中的元素,ArrayList中的其它元素都删除
        Objects.requireNonNull(c);    //同样,集合c不能是空
        return batchRemove(c, true);    //调用batchRemove(),
    }

    private boolean batchRemove(Collection<?> c, boolean complement) {    //私有方法,批量删除
        final Object[] elementData = this.elementData;    //保存数组
        int r = 0, w = 0;    //两个游标,r遍历数组,w指向最新的一个需要保存的元素
        boolean modified = false;    //标记是否修改
        try {
            for (; r < size; r++)    //遍历数组,如果c包含此元素,并且传入的complement为true,或者c不包含该元素,并且传入的complement为false,那么就保留,意味着false是删除,true是保留
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {    //如果没有遍历完成,也就是说c.contains()抛出了异常,将r之后的复制到w之后,更新w
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {    //若果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
            int capacity = calculateCapacity(elementData, size);
            SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, 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();
            }
        }
    }

    public ListIterator<E> listIterator(int index) {    //返回一个ListItr,以index开头
        if (index < 0 || index > size)    //检验index
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    public ListIterator<E> listIterator() {    //返回一个ListItr,以0开头
        return new ListItr(0);
    }

    public Iterator<E> iterator() {    //返回一个Itr,并且是fail-fast的,意味着数组改变之后会报错
        return new Itr();
    }

    /**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {    //定义一个内部类Itr,实现了迭代器接口
        int cursor;       // 下一个要返回的元素下标
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;    //记录下modCount

        Itr() {}    

        public boolean hasNext() {    //判断是否存在下一个
            return cursor != size;    //curse(下一个元素的下标)等于size,意味着没有了下一个元素
        }

        @SuppressWarnings("unchecked")
        public E next() {    //得到下一个元素
            checkForComodification();    //检查modCount,如果和创建迭代器时候的modCount不同,那么就会报错
            int i = cursor;    // 保存下一个元素的下标
            if (i >= size)    //如果下一个返回值大于等于size,抛出异常
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;    //得到数组,因为是内部类,所以要加ArrayList
            if (i >= elementData.length)    //如果i大于等于数组的长度,同样抛出异常
                throw new ConcurrentModificationException();
            cursor = i + 1;    //更新cursor
            return (E) elementData[lastRet = i];    //返回curse下标的元素,并且更新lastRet
        }

        public void remove() {    //删除操作
            if (lastRet < 0)    //如果最后删除的是-1(代表没有迭代过),抛出错误
                throw new IllegalStateException();
            checkForComodification();    //检查modCount是否正确

            try {
                ArrayList.this.remove(lastRet);    //删除最后一个修改的元素
                cursor = lastRet;    //更新cursor
                lastRet = -1;    //更新lastRet为-1,这意味着不能来连续删除两次
                expectedModCount = modCount;    //更新expectedModCount,因为删除之后modCount会改变,所以需要用迭代器的remove()删除,这样会更新expectedModCount,否则如果直接删除ArrayList的元素,modCount改变了,expectedModCount又没改变,这样就会报错
            } 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() {    //检查是否ArrayList是否更改
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    private class ListItr extends Itr implements ListIterator<E> {    //定义一个内部类ListItr,继承了Itr,并且实现了ListIterator接口
        ListItr(int index) {    //构造函数
            super();
            cursor = index;
        }

        public boolean hasPrevious() {    //判断时候有前一个元素,只要cursor不等于0,就有前面一个元素
            return cursor != 0;
        }

        public int nextIndex() {    //返回下一个元素的下标
            return cursor;
        }

        public int previousIndex() {    //返回上一个元素的下标
            return cursor - 1;
        }

        @SuppressWarnings("unchecked")
        public E previous() {    //返回前一个元素
            checkForComodification();    //检查modCount是否改变 
            int i = cursor - 1;    //记录前一个位置
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;    //更新cursor
            return (E) elementData[lastRet = i];    //返回前一个元素
        }

        public void set(E e) {    //设置最后一个返回元素
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();    //检查modCount

            try {
                ArrayList.this.set(lastRet, e);    //将最后一个返回的元素更换
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        public void add(E e) {    //添加某个元素
            checkForComodification();    /检查modCount

            try {
                int i = cursor;
                ArrayList.this.add(i, e);    //将当前游标上添加一个元素
                cursor = i + 1;    //更新cursor
                lastRet = -1;    //更新最后返回的元素下标为-1(因为添加后序号都会变)
                expectedModCount = modCount;    //更新 expectedModCount
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    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) {    //检查from和to的格式,并且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 {    //内部类SubList,继承了AbstractList抽象类,本质上并没有创建一个新的数组,如果对sublist做出改变,都会改变原来的数组
        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) {    //构造函数,参数为一个AbstractList,子数组的头和尾,便偏移
            this.parent = parent;
            this.parentOffset = fromIndex;    //父数组的偏移为fromIndex
            this.offset = offset + fromIndex;    //子数组的偏移为自己的偏移加上父数组的偏移
            this.size = toIndex - fromIndex;    //子数组的负载为需要复制的长度
            this.modCount = ArrayList.this.modCount;    //子数组的modCount等于父数组的modCount
        }

        public E set(int index, E e) {    //将index下标的元素设置为e
            rangeCheck(index);    //检查index的正确性
            checkForComodification();    //检查modCount
            E oldValue = ArrayList.this.elementData(offset + index);    //记录下原来的元素,其为父数组上第(offeset + index)个元素
            ArrayList.this.elementData[offset + index] = e;    //更改元素
            return oldValue;    //返回旧的值
        }

        public E get(int index) {    //获取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;    //更新modCount
            this.size++;
        }

        public E remove(int index) {    //删除一个元素
            rangeCheck(index);
            checkForComodification();
            E result = parent.remove(parentOffset + index);
            this.modCount = parent.modCount;
            this.size--;
            return result;
        }

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

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

        public boolean addAll(int index, Collection<? extends E> c) {
            rangeCheckForAdd(index);
            int cSize = c.size();
            if (cSize==0)
                return false;

            checkForComodification();
            parent.addAll(parentOffset + index, c);
            this.modCount = parent.modCount;
            this.size += cSize;
            return true;
        }

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

        public ListIterator<E> listIterator(final int index) {
            checkForComodification();
            rangeCheckForAdd(index);
            final int offset = this.offset;

            return new ListIterator<E>() {
                int cursor = index;
                int lastRet = -1;
                int expectedModCount = ArrayList.this.modCount;

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

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

                public boolean hasPrevious() {
                    return cursor != 0;
                }

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

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

                public int nextIndex() {
                    return cursor;
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值