java源码解读之ArrayList

8 篇文章 0 订阅
6 篇文章 0 订阅

还是跟之前几篇源码的一样,相关信息都写在源码里面,直接祭出源码啦~~~

package java.util;

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

/**
 * ArrayList继承AbstractList,实现了List、RandomAccess、Cloneable与Serializable接口
 * 其中,AbstraceList提供了List接口的默认实现(个别方法为抽象方法),List接口定义了列表必须实现的方法,
 * Cloneable接口使得ArrayList可以调用Object.clone方法返回该对象的浅拷贝,
 * RandomAccess与Serializable都是标记接口,接口内没定义任何内容,RandomAccess表示该类支持快速随机访问(也
 * 就是通过下标快速访问),而Serializable接口使得ArrayList可以被序列化与反序列化
 */

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

    /**
     * 定义ArrayList初始容量,默认为10
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 一个空数组,当用户指定该 ArrayList容量为0时,返回该空数组 
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 一个空数组,当用户没有指定 ArrayList 的容量时(即调用无参构造函数),返回的是该数组
	 * 刚创建一个 ArrayList时,其内数据量为0,当用户第一次添加元素时,该数组将会扩容,变成
	 * 默认容量为DEFAULT_CAPACITY(10)的一个数组
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 存储ArrayList元素的Object数组,ArrayList的长度就是该数组的长度,一个空(不是null)的
     * ArrayList对象,其elementData字段引用将指向上面的DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * 数组,当第一个元素添加到该ArrayList中时elementData会被扩大到默认的容量DEFAULT_CAPACITY(10)
     * 该数组被transient关键字修饰,表明ArrayList在序列化时不对该属性进行序列化,因此elementData的内容
     * 不能使用serialization机制来保存
     */
    transient Object[] elementData; 

    /**
     *记录当前的ArrayList中包含多少元素
     */
    private int size;

    /**
     * 构造一个指定初始容量的ArrayList对象,当initialCapacity大于0,则直接初始化指定
     * initialCapacity大小的Object数组,当initialCapacity为0则将使用上面定义的空
     * 数组EMPTY_ELEMENTDATA
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * 当不指定初始容量构造ArrayList对象时,使用上面定义的空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 使用一个指定Collection实现类的对象构造ArrayList对象
     */
    public ArrayList(Collection<? extends E> c) {
    	/**
    	 * 先调用Collection实现类的对象的toArray方法返回一个Object数组
    	 * 并赋予ArrayList对象的Object数组(Collection实现类的toArray
    	 * 方法返回的都是Object数组)
    	 */
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            /**
             * 若指定Collection实现类对象存在元素且返回的不是Object数
             * 组,则使用Arrays.copyOf方法将其转为Object数组
             */
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
        	/**
        	 * 若指定Collection实现类对象的元素为空,则用空数组EMPTY_ELEMENTDATA替代ArrayList的Object数组
        	 */
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * 将当前ArrayList的容量设置为当前实际元素的大小,比如当前ArrayList有10个元素,
     * 而容量为15,调用的方法之后容量会被设置为10
     */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 增加ArrayList对象的容量,在必要的情况下,由参数
     * 'minCapacity'指定以确保它至少能容纳所有元素
     */
    public void ensureCapacity(int minCapacity) {
    	/**
    	 * 若该ArrayList实例的Object数组使用的不是默认的DEFAULTCAPACITY_EMPTY_ELEMENTDATA数组(只
    	 * 有当初始化时候ArrayList中元素为空时才会使用该默认数组),最小扩容量为0,其余默认为10,这也是上面
    	 * 说的,当ArrayList使用的是默认的DEFAULTCAPACITY_EMPTY_ELEMENTDATA数组时,第一次添加元素数组
    	 * 会扩容到10
    	 */
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)?0: DEFAULT_CAPACITY;
        
        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

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

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
    	/**
    	 * 这个属性是用于记录该ArrayList实例结构改变的次数
    	 */
        modCount++;

        if (minCapacity - elementData.length > 0)
        	//对ArrayList进行扩容
            grow(minCapacity);
    }

    /**
     * 数组缓冲区最大存储容量 
     * 一些 VM 会在一个数组中存储某些数据--->为什么要减去 8 的原因 
     * 尝试分配这个最大存储容量,可能会导致 OutOfMemoryError(当该值 > VM 的限制时) 
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 对ArrayList实例进行扩容
     */
    private void grow(int minCapacity) {
    	//取得扩容前Object数组的容量
        int oldCapacity = elementData.length;
        /**
         * 默认新的容量=老的容量*1.5
         */
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //若新容量依旧小于minCapacity,则新容量=minCapacity
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //若新容量大于数组最大存储容量,则进行大容量分配
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        /**
         * 使用Arrays的copyOf方法复制元素到新的Object
         * 数组并将elementData引用指向新的Object数组 
         */
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

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

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

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

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

    /**
     * 返回当前元素在ArrayList对象中的位置,若不存在则返回-1
     */
    public int indexOf(Object o) {
    	/**
    	 * 若该元素为null,则遍历ArrayList对象的Object数组,判断元素的引
    	 * 用是否指向null,是则返回该元素的下标,注意,遍历的终点是size,而
    	 * 不是Object数组的length,返回的是第一个为null的元素的下标
    	 */
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
        	/**
        	 * 若该元素不为null,按照上面的方式遍历,调用对象的equals方法去判断,
        	 * 区别于上面的==,equals方法比较的是对象的内容,而==比较的是引用指向
        	 * 的地址
        	 */
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        //若元素不存在则返回-1
        return -1;
    }

    /**
     * 返回当前元素在ArrayList对象最后的位置,不存在则返回-1,
     * 处理逻辑与indexOf方法一样,只是遍历方向相反而已
     */
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /**
     * 简单介绍浅拷贝与深拷贝的区别:
     * 浅拷贝:浅拷贝会对"主"对象进行拷贝,但不会复制主对象里面的对象,
     * "里面的对象"会在原来的对象和它的副本之间共享,两个"主"对象不是
     * 独立的,修改"里面的对象"会互相影响(原始类型会直接拷贝)
     * 深拷贝:深拷贝是一个整个独立的对象拷贝,是整个对象的结构都进行拷贝
     * 
     * String类型不用为其创建深拷贝便可以对其进行共享,因为是不可变对象
     */
    /**
     *返回当前ArrayList对象的浅拷贝,不拷贝ArrayList中元素的原型
     */
    public Object clone() {
        try {
        	/**
        	 * 直接调用Cloneable接口的clone方法复制出一个副本,然后
        	 * 把原ArrayList的元素复制到副本中
        	 */
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }

    /**
     * 将ArrayList对象的Object数组复制到一个新的Object数组中并返回
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * 将ArrayList对象中的Object数组复制到传递进来的数组中
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
    	/**
    	 * 若传入数组的长度小于size,返回一个新的数组,大小为size,类型与传入数组相同
    	 */
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        /**
         * 所传入数组长度与size相等,则将elementData复制到传入数组中并返回传入的数组
         */
        System.arraycopy(elementData, 0, a, 0, size);
        /**
         * 若传入数组长度大于size,除了复制elementData外,还将把返回数组的第size个元素置为null
         */
        if (a.length > size)
            a[size] = null;
        return a;
    }

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

    /**
     *返回ArrayList对象指定位置上的元素
     */
    public E get(int index) {
    	/**
    	 * 检查传入的index是否越界,越界则抛IndexOutOfBoundsException异常
    	 */
        rangeCheck(index);
        //直接返回指定下标的数组元素
        return elementData(index);
    }

    /**
     * 使用新元素替换指定位置的旧元素,并返回旧元素
     */
    public E set(int index, E element) {
    	/**
    	 * 检查传入的index是否越界,越界则抛IndexOutOfBoundsException异常
    	 */
        rangeCheck(index);
        /**
         * 获取旧元素,将新元素设置到ArrayList对
         * 象的Object数组的指定位置,返回旧元素
         */
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    /**
     * 将元素添加到ArrayList对象列表的末尾
     */
    public boolean add(E e) {
    	/**
    	 * 放入元素之前调用ensureCapacityInternal方法确保列表容量
    	 * 足够,更多的是增加结构改变次数,若容量不足则进行扩容
    	 */
        ensureCapacityInternal(size + 1); 
        /**
         * 将元素放入数组末尾
         */
        elementData[size++] = e;
        return true;
    }

    /**
     * 将元素添加到指定下标的位置
     */
    public void add(int index, E element) {
    	/**
    	 * 检查传入的index是否越界,越界则抛IndexOutOfBoundsException异常
    	 */
        rangeCheckForAdd(index);
        /**
    	 * 放入元素之前调用ensureCapacityInternal方法确保列表容量
    	 * 足够,更多的是增加结构改变次数,若容量不足则进行扩容
    	 */
        ensureCapacityInternal(size + 1);  
        /**
         * 调用System.arraycopy将elementData从index开始的size-index个元
         * 素复制到index+1至size+1的位置(即index开始的size-index个元素都向后移动一个位置)
         */
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //将元素放入index位置,size自增
        elementData[index] = element;
        size++;
    }

    /**
     * 移除ArrayList对象指定位置的元素
     */
    public E remove(int index) {
    	/**
    	 * 检查传入的index是否越界,越界则抛IndexOutOfBoundsException异常
    	 */
        rangeCheck(index);
        //结构改变次数加1
        modCount++;
        //获取旧元素,以便返回
        E oldValue = elementData(index);
        //计算需要移动的元素个数
        int numMoved = size - index - 1;
        if (numMoved > 0)
        	//index+1开始的numMoved个元素向前移动一个位置
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //将指定位置上的元素置为null
        elementData[--size] = null; // clear to let GC do its work
        //返回旧元素
        return oldValue;
    }

    /**
     * 移除ArrayList对象中第一个与指定对象相等的元素,若不存在ArrayList不发生改变,
     * 处理逻辑与indexOf方法类似,遇到匹配的对象则执行fastRemove方法移除,数组元素
     * 向前移动一个位置(当对象恰好在最后位置时不移动)
     */
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

    /*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    private void fastRemove(int index) {
    	//结构改变次数加1
        modCount++;
        //计算需要移动的元素个数
        int numMoved = size - index - 1;
        if (numMoved > 0)
        	//index+1开始的numMoved个元素向前移动一个位置
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //将指定位置上的元素置为null
        elementData[--size] = null; // clear to let GC do its work
    }

    /**
     * 移除ArrayList对象中所有的元素,即把Object数组中的元素都移除
     */
    public void clear() {
    	//结构改变次数加1
        modCount++;
        /**
         * 遍历Object数组,将所有位置上的元素置为null
         */
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        //size归零
        size = 0;
    }

    /**
     * 将指定集合里面的元素添加到ArrayList对象列表的末尾
     */
    public boolean addAll(Collection<? extends E> c) {
    	//将指定集合里面的元素以Object数组形式返回
        Object[] a = c.toArray();
        //计算指定集合的元素个数
        int numNew = a.length;
        /**
    	 * 放入元素之前调用ensureCapacityInternal方法确保列表容量
    	 * 足够,更多的是增加结构改变次数,若容量不足则进行扩容
    	 */
        ensureCapacityInternal(size + numNew); 
        //调用System.arrayCopy方法将指定集合的Object数组添加到ArrayList对象的末尾
        System.arraycopy(a, 0, elementData, size, numNew);
        //更新ArrayList对象的size
        size += numNew;
        return numNew != 0;
    }

    /**
     * 将指定集合的元素添加到ArrayList指定位置后面
     */
    public boolean addAll(int index, Collection<? extends E> c) {
    	/**
    	 * 检查传入的index是否越界,越界则抛IndexOutOfBoundsException异常
    	 */
        rangeCheckForAdd(index);
        //将指定集合里面的元素以Object数组形式返回
        Object[] a = c.toArray();
        //计算指定集合的元素个数
        int numNew = a.length;
        /**
    	 * 放入元素之前调用ensureCapacityInternal方法确保列表容量
    	 * 足够,更多的是增加结构改变次数,若容量不足则进行扩容
    	 */
        ensureCapacityInternal(size + numNew);  // Increments modCount
        //计算需要移动的元素个数
        int numMoved = size - index;
        if (numMoved > 0)
        	//index开始的numMoved个元素向后移动numNew个位置
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
        //调用System.arrayCopy方法将指定集合的Object数组添加到ArrayList对象指定位置的末尾
        System.arraycopy(a, 0, elementData, index, numNew);
        //更新ArrayList对象的size
        size += numNew;
        return numNew != 0;
    }
// 0 1 2 3 4 5 6 7 8 9
//       3 4 5 6 7
// 0 1 2           8 9
    /**
     *移除ArrayList对象[fromIndex,toIndex)范围内的元素
     */
    protected void removeRange(int fromIndex, int toIndex) {
    	//结构改变次数加1
        modCount++;
        //计算需要移动的元素个数
        int numMoved = size - toIndex;
        //toIndex开始的numMoved个元素移动到fromIndex开始的位置
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);
        //计算ArrayList对象的size
        int newSize = size - (toIndex-fromIndex);
        //遍历ArrayList对象的Object数组,将[fromIndex,toIndex)范围内的元素置为null
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        //更新ArrayList对象的size
        size = newSize;
    }

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

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

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

    /**
     * 移除ArrayList对象中与指定集合元素匹配的元素
     */
    public boolean removeAll(Collection<?> c) {
    	//确保指定集合不为null,否则抛NullPointerException异常
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    /**
	 * 保存ArrayList对象中与指定集合元素匹配的元素,即移除所有在指定集合中不包含的元素
     */
    public boolean retainAll(Collection<?> c) {
    	//确保指定集合不为null,否则抛NullPointerException异常
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    /**
     * complement为true时从Object数组保留指定集合中的
     * 元素,为false时从Object数组删除指定集合中的元素
     */
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
        	/**
        	 * 遍历Object数组,并检查指定集合是否包含对应的元素,移动要保留的元素到
        	 * Object数组前面,w最终的值为要保留的元素的数量
        	 * 简单点儿说,要保留,就将相同的元素移动到Object数组前段;要删除,就将不
        	 * 同的元素移动到Object数组的前段
        	 */
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            /**
             * finally块确保异常抛出前,遍历过的元素可以完成期望的操作,而未被遍历的部分
             * 会被接到后面
        	 * r!=size时,表示可能出异常,c.contains(elementData[r])抛出的
        	 */
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            /**
        	 * 若w==size,则表示全部元素都保留了,因此也就没发生删除操作,返回false;反
        	 * 之,返回true,并更改数组
        	 * 而当w!=size时,即使try块抛异常,也能正确处理异常抛出前的操作,因为w始终
        	 * 为要保存的前段部分,数组也不会因此而乱序
        	 */
            if (w != size) {
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;//更新结构改变的次数
                size = w;//新的size为保留的元素的个数
                modified = true;
            }
        }
        return modified;
    }

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

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

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

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

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

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

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

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

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

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

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

    /**
     * 以适当的顺序返回ArrayList对象的中
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * ArrayList普通的迭代器实现
     */
    private class Itr implements Iterator<E> {
        int cursor;       // 要返回的下一个元素的下标位置
        int lastRet = -1; // 要返回的最后一个元素的下标位置,没有则返回-1
        int expectedModCount = modCount;//记录当前集合机构改变的次数,用于防止迭代遍历过程中改变集合

        public boolean hasNext() {
            return cursor != size;
        }
        
        //获取当前迭代到的元素
        @SuppressWarnings("unchecked")
        public E next() {
        	/**
        	 * 判断当前集合是否被改变,迭代过程中集合不可改变,否
        	 * 则抛ConcurrentModificationException异常
        	 */
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
        //在集合中移除当前迭代的元素,迭代不会受影响
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            /**
        	 * 判断当前集合是否被改变,迭代过程中集合不可改变,否
        	 * 则抛ConcurrentModificationException异常
        	 */
            checkForComodification();

            try {
            	/**
            	 * 在集合中移除当前元素,但不会影响到迭代器的迭代,remove会改变当前集合的modCount值
            	 */
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                /**
                 * 由于在这里将当前集合的modCount赋予expectedModCount,因此checkForComodification
                 * 方法不会抛ConcurrentModificationException异常
                 */
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        /**
         * 为每个剩余元素执行给定的操作,直到所有的元素都已经被处理或行动将抛出一个异常
         */
        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

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

    /**
     * ArrayList特有的迭代器实现
     */
    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }
        //判断是否有前一个元素
        public boolean hasPrevious() {
            return cursor != 0;
        }
        //获取下一个元素的位置
        public int nextIndex() {
            return cursor;
        }
        //获取前一个元素的位置
        public int previousIndex() {
            return cursor - 1;
        }
        //获取前一个元素
        @SuppressWarnings("unchecked")
        public E previous() {
        	/**
        	 * 判断当前集合是否被改变,迭代过程中集合不可改变,否
        	 * 则抛ConcurrentModificationException异常
        	 */
            checkForComodification();
            //获取前一个元素的下标
            int i = cursor - 1;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            //把下标移动到前一个位置
            cursor = i;
            return (E) elementData[lastRet = i];
        }

        /**
         * 使用新元素替换lastRet位置的旧元素,并返回旧元素
         */
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            /**
        	 * 判断当前集合是否被改变,迭代过程中集合不可改变,否
        	 * 则抛ConcurrentModificationException异常
        	 */
            checkForComodification();

            try {
            	/**
            	 * ArrayList的set方法不会导致modCount发生改变,因此
            	 * 不会抛出ConcurrentModificationException异常
            	 */
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        /**
         * 将元素添加到cursor位置
         */
        public void add(E e) {
        	 /**
        	 * 判断当前集合是否被改变,迭代过程中集合不可改变,否
        	 * 则抛ConcurrentModificationException异常
        	 */
            checkForComodification();

            try {
                int i = cursor;
                //调用ArrayList的add方法添加元素
                ArrayList.this.add(i, e);
                //下标后移一位
                cursor = i + 1;
                lastRet = -1;
                /**
                 * 由于在这里将当前集合的modCount赋予expectedModCount,因此checkForComodification
                 * 方法不会抛ConcurrentModificationException异常
                 */
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * 以一个新的集合返回ArrayList对象[fromIndex,toIndex)范围内的元素
     */
    public List<E> subList(int fromIndex, int toIndex) {
    	//检查下标范围是否合法
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

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

    /**
     * SubList的实现与ArrayList的类似,不多做说明
     * @author linxiaorui
     *
     */
    private class SubList extends AbstractList<E> implements RandomAccess {
        private final AbstractList<E> parent;
        private final int parentOffset;
        private final int offset;
        int size;

        SubList(AbstractList<E> parent,
                int offset, int fromIndex, int toIndex) {
            this.parent = parent;
            this.parentOffset = fromIndex;
            this.offset = offset + fromIndex;
            this.size = toIndex - fromIndex;
            this.modCount = ArrayList.this.modCount;
        }

        public E set(int index, E e) {
            rangeCheck(index);
            checkForComodification();
            E oldValue = ArrayList.this.elementData(offset + index);
            ArrayList.this.elementData[offset + index] = e;
            return oldValue;
        }

        public E get(int index) {
            rangeCheck(index);
            checkForComodification();
            return ArrayList.this.elementData(offset + index);
        }

        public int size() {
            checkForComodification();
            return this.size;
        }

        public void add(int index, E e) {
            rangeCheckForAdd(index);
            checkForComodification();
            parent.add(parentOffset + index, e);
            this.modCount = parent.modCount;
            this.size++;
        }

        public E remove(int index) {
            rangeCheck(index);
            checkForComodification();
            E result = parent.remove(parentOffset + index);
            this.modCount = parent.modCount;
            this.size--;
            return result;
        }

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

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

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

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

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

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

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

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

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

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

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

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

                public int nextIndex() {
                    return cursor;
                }

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

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

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

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

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

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

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

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

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

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

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

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

        private void checkForComodification() {
            if (ArrayList.this.modCount != this.modCount)
                throw new ConcurrentModificationException();
        }
        /**
         * 返回SubList对象的一个可分割迭代器,下面会介绍
         */
        public Spliterator<E> spliterator() {
            checkForComodification();
            return new ArrayListSpliterator<E>(ArrayList.this, offset,
                                               offset + this.size, this.modCount);
        }
    }

    @Override
    public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
     * list.
     *
     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
     * Overriding implementations should document the reporting of additional
     * characteristic values.
     *
     * @return a {@code Spliterator} over the elements in this list
     * @since 1.8
     */
    @Override
    public Spliterator<E> spliterator() {
        return new ArrayListSpliterator<>(this, 0, -1, 0);
    }

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

        /**
         *可分割迭代器,类比于我们常用的Iterator顺序遍历迭代器,Iterator是顺序对元素进行遍历的,
         *而可分割迭代器则可以进行并行的遍历,在现在多核的时代,顺序遍历已无法满足需求,因此为发挥
         *多核的优势,可以将集合的迭代器分割成多个部分,分配到不同的核上执行,于是就有了可分割迭代
         *器Spliterator,jdk1.8每一个集合都有其自己默认的Spliterator实现,ArrayList默认的
         *Spliterator实现就是基于"二分法"的Spliterator
         */

    	//用于存放ArrayList对象
        private final ArrayList<E> list;
        private int index; //起始位置(包含),执行advance或split操作时会改变
        private int fence; //结束位置(不包含),-1表示到最后一个元素
        private int expectedModCount; //用于存放ArrayList的modCount的值

        /** 创建一个覆盖给定范围的ArrayList可分割迭代器 */
        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
                             int expectedModCount) {
            this.list = list; 
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        /**
         * 获取结束位置,首次初始化时需要对fence与expectedModCount进行赋值
         * @return
         */
        private int getFence() { 
            int hi; 
            ArrayList<E> lst;
            //只有当第一次进行初始化化时,fence才会小于0
            if ((hi = fence) < 0) {
                if ((lst = list) == null)
                    hi = fence = 0;
                else {
                	//其他情况,fence就是集合元素的个数
                    expectedModCount = lst.modCount;
                    hi = fence = lst.size;
                }
            }
            return hi;
        }

        /**
         * 分割list,返回一个新分割出的spliterator实例,类似"二分法"
         */
        public ArrayListSpliterator<E> trySplit() {
            int hi = getFence(), //当前结束位置,"最高位"
            lo = index, //当前起始位置,"最低位"
            mid = (lo + hi) >>> 1;//计算"中间位置"
            return (lo >= mid) ? null ://当lo>=mid,表示不能在分割,返回null
            	当lo<mid时,可分割,切割(lo,mid)出去,同时更新index=mid("二分法"也是这样的吧)
                new ArrayListSpliterator<E>(list, lo, index = mid,expectedModCount);
        }

        //对单个元素执行给定的动作,如果有剩下元素未处理返回true,否则返回false
        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null)
                throw new NullPointerException();
            int hi = getFence(), i = index;
            //i<hi,起始位置<结束位置,自然表示还有一下个元素
            if (i < hi) {
                index = i + 1;//当前元素执行给定动作,起始位置index加1
                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
                action.accept(e);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        /**
         * 对每个剩余元素执行给定的动作,依次处理,直到所有元素已被处理或被异常终
         * 止,Spliterator中默认是循环调用tryAdvance方法
         */
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi, mc; // hoist accesses and checks from loop
            ArrayList<E> lst; Object[] a;
            if (action == null)
                throw new NullPointerException();
            if ((lst = list) != null && (a = lst.elementData) != null) {
            	//表示第一次初始化,fence<0,应先进行初始化
                if ((hi = fence) < 0) {
                    mc = lst.modCount;
                    hi = lst.size;
                }
                else
                    mc = expectedModCount;
                if ((i = index) >= 0 && (index = hi) <= a.length) {
                    for (; i < hi; ++i) {
                        @SuppressWarnings("unchecked") E e = (E) a[i];
                        action.accept(e);
                    }
                    if (lst.modCount == mc)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

        //计算还剩下多少元素需要遍历
        public long estimateSize() {
            return (long) (getFence() - index);
        }

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

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值