ArrayList源码分析

ArrayList基础认识

ArrayList 实现了 List 接口,是一个有序容器,即存放元素的顺序与添加顺序相同,允许添加相同元素,包括 null ,底层通过数组来实现数据存储,容器内存储的元素个数不能超出数组空间。当向容器中添加元素时如果发现数组空间不足,容器会自动对底层数组进行扩容操作

ArrayList源码全解析


package list;

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


public class ArrayList extends AbstractList
        implements List, RandomAccess, Cloneable, java.io.Serializable
{
	//序列化id
    private static final long serialVersionUID = 8683452581122892189L;

    //集合默认的长度
    private static final int DEFAULT_CAPACITY = 10;

   //集合大小设置为0时对应的数组
    private static final Object[] EMPTY_ELEMENTDATA = {};

   //初始化使用无参构造器时对应的数组,即 List list = new ArrayList<>();
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
	*包含实际元素的数组 注意这里使用的关键字 transient 这个是让其不被序列化
	* 举个栗子 即A传递一个数组到B 其实实际的元素并没有进行传递
	* 这么做的好处:节省存储空间
	* 问题来了,实际的元素并没有被序列化传输,那么为什么传输后的数据却并没有丢失?
     * 当我们get操作元素时,我们是直接从数组中去取,整个数组的序列化意义不大,反而会消耗比较大的存储空间
     * 这里我们可以看到当前类为泛型类,但存储的数组又变成了Object,是不是有点奇怪?
     * 这个在后面的 集合转数组进行了处理,即生成元素对应类型的数组
	*/

    transient Object[] elementData; 

    //集合大小
    private int size;

    /**
     * 有参构造器
     *
     * @param  initialCapacity  集合的初始长度 这里面Capacity 翻译为能力,我们可以理解为长度
     * @throws IllegalArgumentException 非法异常 此时长度只能为正整数
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * 无参构造器,将前面定义的数组给到实际的数组
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 有参构造器,给了初始元素
     *
     * @param c 实现了Collection的元素 c
     * @throws NullPointerException 元素为空
     */
    public ArrayList(Collection c) {
        elementData = c.toArray();
        //这里是一个先赋值,再比较
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 创建了大小为0的集合
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * modCount 记录集合原来的长度,不可序列化,通过与扩展后的长度比较,判断结构是否发生变化
     *移除不包含元素的数组空间,将数组的空间缩减到和集合 同个大小size
     */
    public void trimToSize() {
        //每当集合的结构发生变化时,modCount 就会递增
        //当在对集合进行迭代操作时,迭代器会检查此参数值
        //如果检查到此参数的值发生变化,就说明在迭代的过程中集合的结构发生了变化,因此会直接抛出异常
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 确保长度(初始长度)
     *
     * @param   minCapacity   最小长度
     */
    public void ensureCapacity(int minCapacity) {

        //默认的最小长度,这个三元表达式的意思是 如果实际元素的个数为0,则数组分配内存为0,否则分配10个内存空间
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            ? 0
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            //当minCapacity大于默认的最小长度,我们需要扩容,即让数组变长
            ensureExplicitCapacity(minCapacity);
        }
    }
    //确保长度(add添加操作时,readObject读取操作时,我们可以通过方法查找找到这些)
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            //对无参构造即 默认长度为10 对比当前长度 取最大的值
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        //这里统一进行操作后的长度进行确保长度处理
        ensureExplicitCapacity(minCapacity);
    }

    //确保长度(add添加操作后,readObject读取操作后)
    private void ensureExplicitCapacity(int minCapacity) {
        //当集合的结构发生变化时,modCount 就会递增
        modCount++;

        // 这里进行判断,即操作后的长度大于数组本身已有的长度,需要扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * 数组分配的最大值
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 扩容
     *
     * @param minCapacity 需要扩展到的长度
     */
    private void grow(int minCapacity) {
        // 扩展前的长度
        int oldCapacity = elementData.length;
        //扩展后的长度 即原长度的1.5倍 右移以为/2
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //1.5倍长度如果小于需要扩展到的长度,则直接将需要扩展的长度 赋予扩展后的长度
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //如果扩展后的长度大于数组分配的最大值,则进行 执行巨大长度方法
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // 将元素复制到新的数组,且分配新的存储空间
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    // 需要扩展到的长度大于数组分配的最大值,则给予Integer的最大值,反之给予数组分配的最大值
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    /**
     *集合的大小
     */
    public int size() {
        return size;
    }

    /**
     * 集合是否为空
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 集合是否包含对象 o
     */
    public boolean contains(Object o) {
        //根据o对象是否在数组索引来判断是否包含
        return indexOf(o) >= 0;
    }

    /**
     * 获取对象 o 的索引
     * -1 找不到对象 o 的索引,即数组不包含该对象
     * 这里对o进行了判空处理( 对象 o 可能为空)
     */
    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;
    }

    /**
     * 获取对象 o 的最后一个索引
     * -1 找不到对象 o 的索引,即数组不包含该对象
     * 可容易知道 indexOf是获得第一个索引,ArrayList可以存储相同的元素
     */
    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;
    }

    /**
     * 克隆,这是所有类都有的方法
     */
    public Object clone() {
        try {
            ArrayList v = (ArrayList) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            //新的集合,变为0
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    /**
     * 集合转数组(返回的是Object对象)
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * 集合转数组(返回的对象根据传入的数组对象一直)
     */
    public  T[] toArray(T[] a) {
        if (a.length < size)
            // 新的数组,使用泛型给定对象类型
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        //将elementData复制给a
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    // 通过索引访问元素
    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);
        //这里原来集合的元素对应数组中索引位置所有的元素,进行赋值操作后,
        // 这个对应关系一直不变,所以返回的仍是 oldValue
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    /**
     * 添加元素
     */
    public boolean add(E e) {
        //集合大小+1,需要考虑数组是否需要扩容
        ensureCapacityInternal(size + 1);
        //数组赋值
        elementData[size++] = e;
        return true;
    }

    /**
     * 指定索引添加元素
     */
    public void add(int index, E element) {
        //对于添加的索引检查
        rangeCheckForAdd(index);
        //添加元素时确保长度方法
        ensureCapacityInternal(size + 1);
        //复制新的数组。将index后的元素后移
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //index位置放入需添加的元素
        elementData[index] = element;
        //集合长度+1
        size++;
    }

    /**
     * 移除指定索引的值,返回该元素
     */
    public E remove(int index) {
        rangeCheck(index);
        //当集合的结构发生变化时,modCount 就会递增
        modCount++;
        //得到索引元素
        E oldValue = elementData(index);
        //进行移动次数计算,因为数组存储是连续的空间
        int numMoved = size - index - 1;
        //删除最后一位元素,数组不需要移动,此时numMoved为0,所以要进行判断
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //此处帮助GC 因为最后一位索引失去了引用
        elementData[--size] = null;

        return oldValue;
    }

    /**
     * 移除集合中的对象 o (第一个)
     * 成功移除返回true反之为false
     */
    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 就会递增
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null;
    }

    /**
     * 清空list
     */
    public void clear() {
        //当集合的结构发生变化时,modCount 就会递增
        modCount++;

        // 此处帮助GC
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        //集合长度设为0
        size = 0;
    }

    /**
     * 添加实现Collection接口的集合 c
     */
    public boolean addAll(Collection c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        //添加时的长度判断
        ensureCapacityInternal(size + numNew);
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

    /**
     * 指定索引位置添加数据集c
     */
    public boolean addAll(int index, Collection c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        //添加时的长度判断
        ensureCapacityInternal(size + numNew);

        //进行移除次数的计算
        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 就会递增
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // 新的集合长度
        int newSize = size - (toIndex-fromIndex);
        //此处帮助GC
        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));
    }

    /**
     * 得到一个字符串,
     * 根据索引得到含索引和长度的字符串
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /**
     * 移除集合中所有 c 包含的相同元素
     */
    public boolean removeAll(Collection c) {
        //非空检查
        Objects.requireNonNull(c);
        //返回值为批量移除的结果
        return batchRemove(c, false);
    }

    /**
     * 只保留集合和 c 包含的相同数据
     */
    public boolean retainAll(Collection c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    //批量移除
    //如果有改动到集合,则返回 true,否则返回 false
    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++)
                //elementData 中符合条件的元素将逐渐从尾部向头部集中
                // complement为true时,即elementData中有和c相同的元素,且元素想数组头部集中
                // complement为false时,即elementData中没有和c相同的元素,且元素想数组头部集中
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            //排除空集合进行removeAll或retainAll操作
            if (r != size) {
                //得到新的数组
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            //新的数组和原数组长度不一样(减小)
            if (w != size) {
                // //此处帮助GC
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                //当集合的结构发生变化时,modCount 就会递增
                modCount += size - w;
                size = w;
                //有改动,返回true
                modified = true;
            }
        }
        return modified;
    }

    /**
     * 写入对象,因为集合中元素可能是对象,对象可能有多个属性,进行序列化读写比较繁琐
     * 此时要求元素必须序列化
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        //记录新的集合的结构,通过modCount
        int expectedModCount = modCount;
        //通过数据流写入对象
        s.defaultWriteObject();

        // 写入集合长度
        s.writeInt(size);

        // 写入每个元素
        for (int i=0; i 0) {
            // 确保长度
            ensureCapacityInternal(size);

            Object[] a = elementData;
            // 依次读出
            for (int i=0; i listIterator(int index) {
        //索引不合法
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * 默认的集合元素迭代器,即索引为0
     */
    public ListIterator listIterator() {
        return new ListItr(0);
    }

    /**
     * 返回集合迭代器
     */
    public Iterator iterator() {
        return new Itr();
    }

    /**
     * 集合迭代器 类
     */
    private class Itr implements Iterator {
        // 指向下一个元素的索引
        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递增
            cursor = i + 1;
            //新的数组元素赋值并返回
            return (E) elementData[lastRet = i];
        }

        //移除
        public void remove() {
            //元素位置移除
            if (lastRet < 0)
                throw new IllegalStateException();
            //检查
            checkForComodification();

            try {
                //开始移除指定索引位置(lastRet)的元素
                ArrayList.this.remove(lastRet);
                //cursor应递减,从上知 原来 lastRet+1,此时lastRet
                cursor = lastRet;
                //最后给到-1 表示移除完毕了
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        //遍历集合从索引 cursor 开始之后剩下的元素
        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer consumer) {
            //非空检查
            Objects.requireNonNull(consumer);
            //集合长度
            final int size = ArrayList.this.size;
            int i = cursor;
            //corsor超过集合长度,直接返回
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            //corsor超过数组长度,抛出异常
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            //corsor不等于集合大小且  ,调用accept进行遍历
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // 遍历结束后,给cursor lastRet赋值并检查
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        //检查集合的结构是否发生变化
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /**
     * 集合元素迭代器 ,继承集合迭代器
     */
    private class ListItr extends Itr implements ListIterator {
        //构造方法
        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();
            }
        }
    }

    /**
     * 指定起始索引 返回截取新的集合(子集合)
     */
    public List 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 + ")");
    }

    //子集合 基本和、ArrayList类似,不详细注释了
    private class SubList extends AbstractList implements RandomAccess {

        //父集合对象
        private final AbstractList parent;
        private final int parentOffset;
        private final int offset;
        int size;

        //子集合构造方法
        SubList(AbstractList 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();
            //和ArrayList赋值类似
            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 c) {
            return addAll(this.size, c);
        }

        public boolean addAll(int index, Collection 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 iterator() {
            return listIterator();
        }

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

            return new ListIterator() {
                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 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 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 spliterator() {
            checkForComodification();
            return new ArrayListSpliterator(ArrayList.this, offset,
                                               offset + this.size, this.modCount);
        }
    }

    //遍历集合元素
    @Override
    public void forEach(Consumer action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        //如果 modCount 值被改动,则直接停止遍历并抛出异常
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            //将集合元素依次传递给 accept 方法
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * 返回可分割迭代器
     */
    @Override
    public Spliterator spliterator() {
        return new ArrayListSpliterator<>(this, 0, -1, 0);
    }

    /** ArrayList可分割迭代器*/
    static final class ArrayListSpliterator implements Spliterator {

        /*
         *
         */

        private final ArrayList list;
        // 起始位置(包含),advance/split操作时会修改
        private int index;
        //结束位置(不包含),-1 表示到最后一个元素
        private int fence;
        // 结束时的ModCount
        private int expectedModCount;

        /** 构造器 */
        ArrayListSpliterator(ArrayList list, int origin, int fence,
                             int expectedModCount) {
            this.list = list;
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        //结束位置获取
        // 首次初始化石需对fence和expectedModCount进行赋值
        private int getFence() {
            int hi;
            ArrayList lst;
            if ((hi = fence) < 0) {
                if ((lst = list) == null)
                    hi = fence = 0;
                else {
                    expectedModCount = lst.modCount;
                    hi = fence = lst.size;
                }
            }
            return hi;
        }

        //分割list,返回一个新分割出的spliterator实例
        public ArrayListSpliterator trySplit() {
            //hi为当前的结束位置
            //lo 为起始位置
            //计算中间的位置
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            //当lo>=mid,表示不能在分割,返回null
            //当lo= mid) ? null :
                new ArrayListSpliterator(list, lo, index = mid,
                                            expectedModCount);
        }

        //返回true 时,只表示可能还有元素未处理
        //返回false 时,没有剩余元素处理了。。。
        public boolean tryAdvance(Consumer action) {
            if (action == null)
                throw new NullPointerException();
            //hi为当前的结束位置
            //i 为起始位置
            int hi = getFence(), i = index;
            //还有剩余元素未处理时
            if (i < hi) {
                //处理i位置,index+1
                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 action) {
            int i, hi, mc; // hoist accesses and checks from loop
            ArrayList 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 filter) {
        //非空检查
        Objects.requireNonNull(filter);
        int removeCount = 0;
        //用于标记集合是哪个索引位置需要被移除
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            //条件判断,移除数量递增
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        //遍历时发生结构变更时抛出异常
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

        // 移除操作 只有 removeCount > 0 才说明需要移除元素
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            //集合移除指定元素后的大小
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                //略过被标记为 true 的位置,直接跳到不需要移除元素的数组索引位
                i = removeSet.nextClearBit(i);
                //有效数据逐渐从尾部向头部聚集
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // 垃圾回收,引用置null
            }
            this.size = newSize;
            //遍历时发生结构变更时抛出异常
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

    //将集合元素遍历传递给 operator,并将原始数据替换为 operator 的返回值
    @Override
    @SuppressWarnings("unchecked")
    public void replaceAll(UnaryOperator operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            //依次传递数组元素给 apply 方法,并将其返回值替换原始数据
            elementData[i] = operator.apply((E) elementData[i]);
        }
        //遍历时发生结构变更时抛出异常
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    //将集合按照指定规则进行排序
    @Override
    @SuppressWarnings("unchecked")
    public void sort(Comparator c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        //遍历时发生结构变更时抛出异常
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }
}

 

你可能感兴趣的:(java从入门到精通笔记)