ArrayList源码分析_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > ArrayList源码分析

ArrayList源码分析

 2018/6/20 18:20:27  David_Wrong  程序员俱乐部  我要评论(0)
  • 摘要:/***可调整大小的数组的列表接口的实现。*实现List接口的所有可选的操作,并允许添加任何元素,包括NULL。*除了实现列表接口之外,该类还提供了方法来操作内部存储数组的数组的大小。(这个类大致相当于Vector,除了它是不同步的)*size,isEmpty,get,set,iterator,和listIterator操作所需要的时间是一个常量。*Add操作所需要的时间是不固定的,也就是说,添加n个元素需要O(n)时间。粗略地说,所有其他操作所需要的时间都是线性的
  • 标签:list 源码 分析
/**
* 可调整大小的数组的列表接口的实现。
* 实现List接口的所有可选的操作,并允许添加任何元素,包括NULL。
* 除了实现列表接口之外,该类还提供了方法来操作内部存储数组的数组的大小。(这个类大致相当于Vector,除了它是不同步的)
* size, isEmpty, get, set, iterator, 和listIterator操作所需要的时间是一个常量。
* Add操作所需要的时间是不固定的,也就是说,添加n个元素需要O(n)时间。粗略地说,所有其他操作所需要的时间都是线性的。
* 每个ARARYLIST实例都具有容量。容量是用来存储列表中元素的数组的大小。它总是至少和列表大小一样大。当元素被添加到数组列表中时,其容量自动增长。
* 增长策略的细节并不是在添加元素具有恒定的时间成本的情况下指定的。
* 在添加大量元素之前,应用程序可以在使用ensureCapacity操作提高ArrayList实例的容量。这可能会减少增量再分配的数量。
* 请注意,此实现不同步。如果多个线程同时访问一个ARARYLAMP实例,并且至少一个线程在结构上修改列表,则必须在外部进行同步。
* (结构修改是任何添加或删除一个或多个元素的操作,或者明确地调整数组的大小;仅仅设置元素的值不是结构修改。)
* 这通常是通过对自然封装列表的一些对象进行同步来实现的。
* 如果不存在这样的对象,则应该使用Collections.synchronizedList方法。这最好在创建时完成,以防止偶然的非同步访问列表:
* List list = Collections.synchronizedList(new ArrayList(...));
* 由该类的iterator()和listIterator(int)方法返回的迭代器是fail-fast:
* 即,在迭代器被创建后,如果迭代器在任何时候对列表进行结构修改,除了通过迭代器自己的remove()或add(Object)方法之外,迭代器将抛出一个ConcurrentModificationException。
* 因此,在并发修改的情况下,迭代器快速且迅速地失败,而不是在未来的不确定时间存在任意的、非确定性的行为。
* 请注意,迭代器的故障fail-fast行为不能得到保证。一般来说,在不同步的并发修改的情况下,不可能做出任何保证,但Fail-fast迭代器会尽最大努力抛出ConcurrentModificationException修改异常
* 因此,编写一个依赖于该异常的程序的正确性是错误的:迭代器的故障快速行为应该只用于检测错误。
*/

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    private static final long serialVersionUID = 8683452581122892189L;
    /**
     * Readme
     * modCount:在ArrayList中有个成员变量modCount,继承于AbstractList。
     *      这个成员变量记录着集合的修改次数,也就每次add或者remove它的值都会加1。
     *      迭代时,如果在读取的过程中,发生移除或添加元素时,避免ArrayIndexOutOfBoundsException异常或少读取添加的元素。
     * transient使用小结(transient Object[] elementData;)
     *      1)一旦变量被transient修饰,变量将不再是对象持久化的一部分,该变量内容在序列化后无法获得访问。
     *      2)transient关键字只能修饰变量,而不能修饰方法和类。注意,本地变量是不能被transient关键字修饰的。变量如果是用户自定义类变量,则该类需要实现Serializable接口。
     *      3)被transient关键字修饰的变量不再能被序列化,一个静态变量不管是否被transient修饰,均不能被序列化。
     */

    /**
     * MAX_ARRAY_SIZE:数组允许分配的最大的内存空间的大小。
     * 由于一些虚拟机需要存储header words,所以为了防止数组大小超出了虚拟机的限制,导致一些机器内存溢出,此处大小定义为Integer.MAX_VALUE-8。
     * 但在扩容方法里,最大还是能扩充到Integer.MAX_VALUE,此处是个疑问!!!!
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    //默认初始化容量
    private static final int DEFAULT_CAPACITY = 10;

    // 共享的空数组实例
    private static final Object[] EMPTY_ELEMENTDATA = {};

    // 用于缺省大小的空实例的共享空数组实例。我们将此与EMPTY_ELEMENTDATA区分开来,以知道在添加第一个元素时要扩充多少。
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 存储数组列表元素的数组缓冲区。
     * 数组的容量是这个数组缓冲器的长度。
     * 当添加第一个元素时,任何带有elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA的空数组都将扩展为DEFAULT_CAPACITY容量。
     */
    transient Object[] elementData; // non-private to simplify nested class access

// ArrayList数组的大小(数组所包含的元素个数)
    private int size;

   
一、构造方法分析
1、无参构造:构造一个空的Object[]数组
    public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}

   2、单参构造(int):构造一个指定容量的Object[]数组
    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);
        }
    }

    3、单参构造(Collection):按照集合迭代器返回的顺序构造包含指定集合元素的列表。
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)//对于此处的注释,不太明白为什么c.toArray可能不返回Object[]
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 如果大小为0,则构建一个空list
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

二、添加方法
1、添加指定元素到这个list集合的末尾
    public boolean add(E e) {
// 此方法主要用于扩展list集合大小,如果是空数组,则初始化数组,默认初始化大小为10
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

2、添加(插入)元素到list中的指定的位置上,并将当前在该位置的元素(如果有的话)和任何后续元素向后移动
    public void add(int index, E element) {
// 检查插入的下标是否越界(index>size || index<0)
        rangeCheckForAdd(index);
// 扩展集合大小(增量计数)
        ensureCapacityInternal(size + 1);
// 复制数组到目标数组:arraycopy(原数组, 原数组的开始位置, 目标数组, 目标数组的开始位置, 复制到目标的长度)
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
// 将elemet放到下标为index的位置上
        elementData[index] = element;
        size++;
    }

3、添加所有:将c中所有的元素追加到list的末尾
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length; // 记录传入数组的大小(长度)
        // 数组扩容
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

   4、添加所有:将c中所有的元素添加到list中的指定位置,如果指定的位置有元素,则将其以及其后的元素向后移动
    public boolean addAll(int index, Collection<? extends E> c) {
        // 检查指定的下标index是否越界
        rangeCheckForAdd(index);
        Object[] a = c.toArray();   // 将c转化成数组
        int numNew = a.length;      // 获取a的数组长度
        ensureCapacityInternal(size + numNew);  // 数组扩容
        int numMoved = size - index;    // 计算需要移动的元素的个数
        // 如果存在需要移动的元素,则将元素后移
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
        // 将a整体插入到list数组中,插入下标是index,插入长度是numNew(a.length)
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

三、删除方法
   1、移除并返回list列表中指定位置的元素,如果指定位置元素之后还有其他元素,则将这些元素全部向左移动
    public E remove(int index) {
        // 判断下标是否越界
        rangeCheck(index);
        modCount++;
        // 通过下标,获取下标所对应的list中的值
        E oldValue = elementData(index);
        // 获取需要移动的元素的个数
        int numMoved = size - index - 1;
        if (numMoved > 0)   // 将元素左移,填充被移除的元素的位置
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        elementData[--size] = null; // 清空元素末尾的值,使GC去执行清理工作
        // 返回该下标所对应的元素的值
        return oldValue;
    }

    2、移除元素:如果这个这个指定元素存在于list中,则移除list中第一次出现的指定元素,并返回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;
    }

   3、移除所有元素:将list中所有的元素都移除
    public boolean removeAll(Collection<?> c) {
        // 判断c是否为null,如果为null则抛NullPointerException,否则返回c
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

   4、清空list列表:将所有的元素置为null,并将size的值置为0
    public void clear() {
        modCount++;
        // 清空去让GC做它的工作
        for (int i = 0; i < size; i++)
            elementData[i] = null;  // 遍历所有元素并将元素置为null
        size = 0;   // 将list的大小置为0
    }

   5、移除
    @Override
    public boolean removeIf(Predicate<? super E> 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();
        }

        // 将剩余元素移到被移除元素留下的空间上
        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;
    }

   6、移除指定区间的元素:移除元素下标在[fromIndex,toIndex)之间的元素,并将元素左移(包含fromIndex但不包含toIndex)
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;  // 记录需要移动的元素的个数
        //将第一个elementData数组里从索引为toIndex的元素开始, 复制到数组第二个elementData里的索引为fromIndex的位置, 复制的元素个数为numMoved个.
        System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
        int newSize = size - (toIndex-fromIndex);   // 计算list的新大小
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;  //将多余的元素置空
        }
        size = newSize; //设置list的大小
    }

四、修改方法
    1、将下标为index位置的元素替换成element
    public E set(int index, E element) {
        rangeCheck(index);  // 数组越界检查(index >= size)
        E oldValue = elementData(index);// 获取index位置上原来的元素
        elementData[index] = element;   // 将index位置上的元素替换成element
        return oldValue;    // 返回index位置上以前的元素
    }

   2、替换所有
    @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++;
    }

五、获取方法
    1、获取下标为index的元素
    public E get(int index) {
        rangeCheck(index);  // 数组越界检查(index >= size)
        return elementData(index);  // 返回下标为index的元素【return (E) elementData[index]】
    }

   2、获取元素o在list中第一次出现的位置的下标值,更准确地来说,返回最小的下标值。如果在list中,o不存在,则返回-1
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    3、获取元素o在list中最后一次出现的位置的下标值,更准确地来说,返回最大的下标值。如果在list中,o不存在,则返回-1
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

   4、获取元素总个数
    public int size() {
        return size;
    }

六、转换/并集/排序方法
    1、转换成Object数组:返回一个以适当顺序(从第一个到最后一个元素)并且包含list中所有元素的Object数组。
        返回的数组将是“安全的”,因为没有引用它。此方法返回的数组是一块新的内存空间。该方法在基于数组和基于集合的API之间起到桥梁的作用。

    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    2、转换成T[]数组:返回一个以适当顺序(从第一个到最后一个元素)并且包含list中所有元素的类型为T的数组。
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)    // 创建一个新数组
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

   3、仅保留包含在该列表中的元素指定集合。换句话说,从这个列表中删除所有未包含在指定集合中的元素的。
    /**
     * 示例:有两个集合newCoures和oldCourses,判断这两个集合是否包含相同的对象或元素,可以使用retainAll方法:oldCourses.retainAll(newCoures)。
     * 如果存在相同元素,oldCourses中仅保留相同的元素。
     * 如果不存在相同元素,oldCourse会变为空。
     */
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    4、排序
    @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++;
    }

七、判空、包含、克隆、扩容、调整list内存方法
    1、判断list中是否为空,判断标准:size==0
    public boolean isEmpty() {
        return size == 0;
    }

    2、判断list列表中是否包含元素o。准确地说,当且仅当list中至少包含一个元素o时,返回true,否则返回false
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

   3、克隆:返回list的一个浅复制的实例,这个元素本身并没有被复制
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    4、扩容:为list扩容。如有必要,增加此list实例的容量,以确保它至少能够容纳最小容量参数所指定的元素数。
    public void ensureCapacity(int minCapacity) {
        // 如果是非空数组则设置minExpand=0;否则设置minExpand=10
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)?0:DEFAULT_CAPACITY;
        if (minCapacity > minExpand) {// 如果minCapacity>minExpan,则扩容
            ensureExplicitCapacity(minCapacity);
        }
    }

   5、调整list所占内存:修整此ArrayList实例的是列表的当前大小的容量。应用程序可以使用此操作,以尽量减少一个ArrayList实例的存储。
    /**
     * ArrayList所说没有用的值并不是null,而是ArrayList每次增长会预申请多一点空间,1.5倍+1,而不是两倍。
     * 这样就会出现当size() = 1000的时候,ArrayList已经申请了1200空间的情况
     * trimToSize作用:去掉预留元素位置,就是删除多余的200,改为只申请1000,内存紧张的时候会用到.
     */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {// 如果size==0则置为空数组,否则复制元素到指定的空间大小
            elementData = (size == 0) ? EMPTY_ELEMENTDATA:Arrays.copyOf(elementData, size);
        }
    }

八、遍历
    1、遍历:按顺序返回list中元素的列表迭代器
    public Iterator<E> iterator() {
        return new Itr();
    }

    2、遍历:返回list中元素的列表迭代器(按顺序)
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

   3、遍历:从列表中的指定位置开始,以适当的顺序返回list迭代器。指定的索引指示将要使用的第一个元素。
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

九、截取子串:
    /**
     * 返回list中下标从fromIndex到toIndex【[formIndex,toIndex)】之间的子串;
     * 如果formIndex==toIndex,返回的列表为空。
     * 返回的列表由该列表支持,因此返回列表中的非结构性更改反映在该列表中。
     * 返回列表支持所有可选列表操作。
     * 此方法消除了对显式范围操作(对于数组通常存在的排序)的需要。
     * 任何期望列表的操作都可以通过传递子视图而不是整个列表作为范围操作。
     * 例如,下面的习惯用法从列表中删除一系列元素:list.subList(from, to).clear();
     * 如果备份列表(即,该列表)通过返回列表以外的任何方式进行结构修改,则该方法返回的列表的语义变得未定义。
     * (结构修改是那些改变这个列表的大小,或者以其他方式扰乱它的方式,即迭代过程中可能会产生不正确的结果。)
     */
    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

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

    private class SubList extends AbstractList<E> implements RandomAccess {
        private final AbstractList<E> parent;
        private final int parentOffset;
        private final int offset;
        int size;

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

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

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

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

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

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

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

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

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

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

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

    //在该列表中创建后期绑定和元素。
    @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;
        }
    }

    // 此方法会移除元素并左移填充,但不会检查下标是否越界
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

    private void ensureCapacityInternal(int minCapacity) {
        // 判断是否是空list,如果是,则初始化其大小为10
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        // 扩展数组容量
        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // 数组扩容处理
        if (minCapacity - elementData.length > 0) grow(minCapacity);
    }

    // 数组扩容:扩充数组容量以确保它能够容纳至少由最小容量参数指定的元素数量
    private void grow(int minCapacity) {
        // 记录原数组的容量
        int oldCapacity = elementData.length;
        // 扩充容量的大小为原数组的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        // 如果容量扩大1.5倍后依旧达不到存储要求,则将传入的值作为数组的容量
        if (newCapacity - minCapacity < 0) newCapacity = minCapacity;
/* 如果扩容1.5倍后,容量超出了数组所允许的容量最大值(MAX_ARRAY_SIZE):
* 判断minCapacity的大小是否超过MAX_ARRAY_SIZE,
* 如果超过了,则扩容后的数组容量为Integer.MAX_VALUE,否则为MAX_ARRAY_SIZE
         */
        if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity);
        // 复制出一个新的数组:最小容量通常接近数组大小
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    // 判断minCanacity的值是否越界(minCapacity<0或minCapacity>MAX_ARRAY_SIZE)
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // 如果小于0则抛出异常
            throw new OutOfMemoryError();
        // 如果大于数组容量的最大值(MAX_ARRAY_SIZE),则返回Integer.MAX_VALUE;
        // 否则返回数组容量的最大值
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }

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

    // 检查数组下标是否越界,在数组被使用前使用
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    // 作用同rangeCheck,检查数组下标是否越界,用于add和addAll方法中
    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;
    }

    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];  // 将符合条件的元素复值按照下标w赋值
        } finally {
            // 即使c.contains()有异常抛出,也保持与抽象集合的行为兼容性。
            if (r != size) {//将第一个elementData数组里从索引为r的元素开始, 复制到数组第二个elementData里的索引为w的位置, 复制的元素个数为(size-r)个.
                System.arraycopy(elementData, r, elementData, w,size - r);
                w += size - r;
            }
            if (w != size) {
                // 将list中的其他不符合条件的元素清空
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;   // 设置list的大小
                modified = true;
            }
        }
        return modified;
    }

    // 将ArryList实例的状态保存到流中(即,序列化它)
    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();
        }
    }

    // 从流中重构ArrayList实例(即:反序列化它。)
    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();
            }
        }
    }

    // AbstractList.Itr的一个优化版本
    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() {
            checkForComodification();// 检查修改次数,防止并发带来的数据误读
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

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

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

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

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

    // AbstractList.ListItr的一个优化版本
    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

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

        public int nextIndex() {
            return cursor;
        }

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

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

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

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

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


}
  • ArrayList源码解析.rar (11.6 KB)
  • 下载次数: 0
上一篇: 给Java字节码加上”翅膀“的JIT编译器 下一篇: 没有下一篇了!
发表评论
用户名: 匿名