1---collection集合之ArrayList原理分析

1.collection集合框架位于java.util工具包。
List—ArrayList

2.ArrayList类源码:

package java.util;

/** * 增删改查列表元素,既可以用它本身的方法get(),set(),remove(),add()方法,也可以用iterator去增删改查。 * 本arrayList是自动扩增容量的。 * Resizable-array implementation of the <tt>List</tt> interface. Implements * all optional list operations, and permits all elements, including * <tt>null</tt>. In addition to implementing the <tt>List</tt> interface, * this class provides methods to manipulate the size of the array that is * used internally to store the list. (This class is roughly equivalent to * <tt>Vector</tt>, except that it is unsynchronized.) * * <p>The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>, * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant * time. The <tt>add</tt> operation runs in <i>amortized constant time</i>, * that is, adding n elements requires O(n) time. All of the other operations * run in linear time (roughly speaking). The constant factor is low compared * to that for the <tt>LinkedList</tt> implementation. * * <p>Each <tt>ArrayList</tt> instance has a <i>capacity</i>. The capacity is * the size of the array used to store the elements in the list. It is always * at least as large as the list size. As elements are added to an ArrayList, * its capacity grows automatically. The details of the growth policy are not * specified beyond the fact that adding an element has constant amortized * time cost. * * <p>An application can increase the capacity of an <tt>ArrayList</tt> instance * before adding a large number of elements using the <tt>ensureCapacity</tt> * operation. This may reduce the amount of incremental reallocation. * * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access an <tt>ArrayList</tt> instance concurrently, * and at least one of the threads modifies the list structurally, it * <i>must</i> be synchronized externally. (A structural modification is * any operation that adds or deletes one or more elements, or explicitly * resizes the backing array; merely setting the value of an element is not * a structural modification.) This is typically accomplished by * synchronizing on some object that naturally encapsulates the list. * * If no such object exists, the list should be "wrapped" using the * {@link Collections#synchronizedList Collections.synchronizedList} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the list:<pre> * List list = Collections.synchronizedList(new ArrayList(...));</pre> * * <p><a name="fail-fast"/> * The iterators returned by this class's {@link #iterator() iterator} and * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>: * if the list is structurally modified at any time after the iterator is * created, in any way except through the iterator's own * {@link ListIterator#remove() remove} or * {@link ListIterator#add(Object) add} methods, the iterator will throw a * {@link ConcurrentModificationException}. Thus, in the face of * concurrent modification, the iterator fails quickly and cleanly, rather * than risking arbitrary, non-deterministic behavior at an undetermined * time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see List * @see LinkedList * @see Vector * @since 1.2 */
//ArrayList继承类:AbstractList类,
//实现接口:List, RandomAccess, Clone, Serializable接口

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

    /** * 默认的elementData数组大小,如果未初始化大小,则按此大小初始化. */
    private static final int DEFAULT_CAPACITY = 10;

    /** * 作为比较或其他用途的空列表数组使用. */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /** * 该数组用来存储实际的列表元素,若是空列表,则在第一次加入元素时,扩充容量为默认值10. * 该数组的大小是可变的,会根据加入元素的数量进行适当扩充。 */
    private transient Object[] elementData;

    /** * size存储列表元素的大小。 */
    private int size;

    /** * 数组列表构造器(参数为指定数组长度). * * @param initialCapacity---数组的大小; * @throws IllegalArgumentException 如果initialCapacity是负数,则抛出非法参数异常。 */
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }

    /** * 构造一个数组大小为默认值10的数组列表. * 刚开始elementData为空列表,在第一次调用add()时,会增加数组大小为10. */
    public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }

    /** * 构造一个包含指定collection集合元素的数组列表 * * @param c 指定的集合元素。 * @throws NullPointerException 如果参数collection是空的,则会抛出空指针异常! */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

    /** * 将elementData数组大小修改为arrayList列表的大小。即capacity = size; * size的大小必须小于capacity; */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = Arrays.copyOf(elementData, size);
        }
    }

    /** * 用于扩充数组的大小; * 首先会根据elementData是否为空表,进行容量选择,是,则默认预设大小为10,否,则为0; * 不为空表,则ensureExplicitCapacity()里面会对minCapacity进行检查, * 必须大于原始数组大小,才会进行扩充。 * @param minCapacity---数组的最小容量 */
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != EMPTY_ELEMENTDATA)
            // any size if real element table
            ? 0
            // larger than default for empty table. It's already supposed to be
            // at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    /** * 用于类内部容量扩充;作用同上述方法 **/
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    /** * 用于容量扩充的具体实现方法,会自动检测minCapacity是否大于原始数组大小。 **/
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /** * 数组elementData所能容纳的元素最大容量。 * 根据VMs的要求,规定了有一些头信息存储在数组里占用了8个位置, * 所以最大容量=Integer.MAX_VALUE - 8; * 如果超出最大容量,则会抛出OutOfMemoryError:Requested array size exceeds VM limit */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /** * 增加容量的具体实现方法。 * 会限制容量大小,进行容量大小检测。 * 超出抛异常 * @param minCapacity the desired minimum capacity */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    /** * 对最大容量检测的具体代码; * 当minCapacity超出最大表示整数时,就会变为负数<0,则抛出overflow异常; * 如果minCapacity < Integer.MAX_VALUE,但 > MAX_ARRAY_SIZE, * 则选择扩充最小容量为Integer.MAX_VALUE;否则,为MAX_ARRAY_SIZE. **/
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    /** * 返回列表元素的大小,不是数组elementData的大小!!! * @return the number of elements in this list */
    public int size() {
        return size;
    }

    /** * 检测列表是否为空,是,则返回true; * * @return <tt>true</tt> if this list contains no elements */
    public boolean isEmpty() {
        return size == 0;
    }

    /** * 检测列表是否包含指定元素o; * * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /** * 返回指定元素对象在数组列表中第一次出现的索引; * 允许列表中有null元素,遍历整个列表,直到遇见指定元素,返回其对应索引。 * 不存在,则返回-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;
    }

    /** * 返回指定元素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;
    }

    /** * * 返回一个列表的浅拷贝;也就是说,只拷贝列表的大小,不拷贝列表元素; * * @return a clone of this <tt>ArrayList</tt> instance */
    public Object clone() {
        try {
            @SuppressWarnings("unchecked")
                ArrayList<E> v = (ArrayList<E>) 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();
        }
    }

    /** * 将列表元素复制到大小=size的新数组中;并返回新数组! * * @return an array containing all of the elements in this list in * proper sequence */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /** * 将数组列表转换为与a数组参数同类型的数组。 * 如果参数a数组的长度<原列表的大小,则返回新的同a数组类型的数组; * 否则,将原数组复制给a数组,若有剩余空间,则赋值为null,最后返回a数组; * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    //返回索引为index的elementData数组中的元素,也是具体的实现方法

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

    /** * 返回索引为index的elementData数组中的元素. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */
    public E get(int index) {
        rangeCheck(index); //核对index索引是否超出范围

        return elementData(index);
    }

    /** * 设置索引为index处的元素为element; * 设置前先检查索引index的范围是否合理。 * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position 返回设置之前的元素 * @throws IndexOutOfBoundsException {@inheritDoc} */
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    /** * 往list中加入元素e,加入到最后边; * 每加入一个元素,数组的大小扩充1个,自增加1。 * 加入成功返回true; * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    /** * 在指定的index处,加入元素element. * 先核对index的范围合理性,在自动扩充1个数组大小, * 再用arraycopy()将index--(size-1)的元素移动到(index+1)--size,即空出index处的位置; * 最后再在index处放入元素。 * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

    /** * 返回删除的index处的的元素。 * 检测index范围,先将index处数据保存在oldValue里面, * 再将(index+1)---(size-1)的元素移动到index---(size-2), * 将多余的size-1处数据设置空null,等待gc收集。 * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */
    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

    /** * 从列表中去除指定的元素。 * 允许为空值null,遍历整个列表,进行删除操作,并返回true; * 否则,返回false; * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */
    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;
    }

    /* * 快速删除的方法,不进行索引检测,也没有返回值。 * 先计算出要移动的元素个数numMoved,若numMoved > 0, * 则将(index+1)---(size-1)的元素移动到index---(size-2)。 * 将多余的size-1处数据设置空null,等待gc收集。 */
    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
    }

    /** * 删除列表中所有的元素,实际是将所有元素置空,等待gc回收,并将size归零。 */
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

    /** * 在列表末尾加入指定collection集合中的所有元素。 * 首先将集合c创建为一个新数组返回给了数组a; * 再扩充原始数组elementData的大小为size + a.length; * 再将a数组中的所有元素放入到elementData数组的size---size+numNew的位置; * 最后再改变size=原始size+numNew. * 返回加入成功信息true. 若c集合为空,则返回false! * * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified collection is null */
    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;
    }

    /** * 在指定的index处加入集合c中的所有元素。 * * @param index index at which to insert the first element from the * specified collection * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException if the specified collection is null */
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index); //进行范围检测

        Object[] a = c.toArray(); //将c集合转换为数组。
        int numNew = a.length; //a数组的长度
        ensureCapacityInternal(size + numNew);  //扩充原始数组大小为size+numNew, Increments modCount

        int numMoved = size - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew, numMoved); 
            //将元素(index---size-1)移动到(index+numNew---size+numNew-1)的位置

        System.arraycopy(a, 0, elementData, index, numNew); //将a中所有元素移动到index--index+numNew-1的位置
        size += numNew; //设置size=size+numNew.
        return numNew != 0;
    }

    /** * 去除一个范围的列表元素从fromIndex到toIndex * * @throws IndexOutOfBoundsException if {@code fromIndex} or * {@code toIndex} is out of range * ({@code fromIndex < 0 || * fromIndex >= size() || * toIndex > size() || * toIndex < fromIndex}) */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex; //要移动的元素个数
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved); //将toIndex后的元素移动到fromIndex开始的位置

        // 清除剩余空间的元素,设置为null,等待gc处理
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize; //设置size=删除后的newSize.
    }

    /** * 检测index范围的具体实现代码,超出列表长度,则抛出IndexOutOfBoundsException. */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /** * add方法专属的index范围检测方法,超出列表长度或index为负数,则抛出IndexOutOfBoundsException. */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /** * 返回index索引异常具体信息提示. * Of the many possible refactorings of the error handling code, * this "outlining" performs best with both server and client VMs. */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /** * 去除所有包含在集合c中的元素,删成功,则返回true;否则,返回false. * * @param c collection containing elements to be removed from this list * @return {@code true} if this list changed as a result of the call * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements * (<a href="Collection.html#optional-restrictions">optional</a>), * or if the specified collection is null * @see Collection#contains(Object) */
    public boolean removeAll(Collection<?> c) {
        return batchRemove(c, false);
    }

    /** * 保留所有包含在集合c中的元素。保留成功,返回true;否则,返回false. * * @param c collection containing elements to be retained in this list * @return {@code true} if this list changed as a result of the call * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements * (<a href="Collection.html#optional-restrictions">optional</a>), * or if the specified collection is null * @see Collection#contains(Object) */
    public boolean retainAll(Collection<?> c) {
        return batchRemove(c, true);
    }

    /* * 具体的批删除方法。 * 参数c---批删除方法相关的集合c,对他与其列表中相同的元素,进行保留或删除。 * 参数complement---是保留还是删除c集合中的元素,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++) //遍历整个元素列表
                if (c.contains(elementData[r]) == complement) //筛选出列表中要保留下来的元素
                    elementData[w++] = elementData[r]; //将要保留的元素赋给elementData数组
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) { //如果中途c.contains()抛出异常,导致未遍历完,即r!=size,进行如下操作
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r); //将未遍历的剩余元素复制到已筛选出保留元素的elementData数组中。
                w += size - r; //顺便也改变其大小。
            }
            if (w != size) { //若有删除了的元素,则进行如下操作
                // clear to let GC do its work
                for (int i = w; i < size; i++) //从列表中最后一个保留下来的元素之后开始遍历
                    elementData[i] = null; // 将剩余元素置空,等待gc处理
                modCount += size - w;
                size = w; //修改列表大小为保留元素个数
                modified = true;
            }
        }
        return modified;
    }

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

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

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

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

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

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

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

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

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

    /** * 构建一个迭代器,从index处开始迭代。 * 先检查索引范围,不符合则抛出异常。 * new ListItr(index)对象 * * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @throws IndexOutOfBoundsException {@inheritDoc} */
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /** * 返回一个ListItr对象,并且从头开始遍历列表。 * * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @see #listIterator(int) */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /** * 返回Itr()对象. * * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @return an iterator over the elements in this list in proper sequence */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /** * An optimized version of AbstractList.Itr */
    private class Itr implements Iterator<E> {
        int cursor;       // 下一个即将要返回的元素索引,也就是说当前的元素索引。
        int lastRet = -1; // 上一个已返回的元素索引,如果没有,则返回-1.
        int expectedModCount = modCount;

        /* * 判断是否存在下一个元素。 * 存在,返回true;否则,返回false. */
        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        /* * 返回下一个元素elementData[cursor]。 * 先判断cursor索引是否符列表范围,不符合则抛出NoSuchElementException。 * 再判断cursor索引是否符elementData原数组的范围,不符合则抛出ConcurrentModificationException。 * cursor移动到下一个元素列表位置。 */
        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];
        }

        /* * 去除lastRet的元素,但每次调用remove()之前,必须先调用next()或previous()方法。 * 否则,会抛出IllegalStateException。 * 之所以先调用next(),previous()方法,因为remove删除的是lastRet,也仅仅前两个方法在最后对lastRet * 进行了赋值。 */
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet; //将cursor索引调整为lastRet, 因为将后边的移动到了lastRet开始的位置(也就是删除了lastRet),所以cursor下一个即将要返回的元素依然为lastRet.
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

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

    /** * An optimized version of AbstractList.ListItr */
    private class ListItr extends Itr implements ListIterator<E> {
        /* * 新建一个从index处开始迭代的ListItr迭代器。 * 设置当前的元素为index. */
        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) //i不能小于零,否则抛出NoSuchElementException
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) //i不能大于数组长度,否则抛出ConcurrentModificationException
                throw new ConcurrentModificationException();
            cursor = i; //为了继续寻找前一个元素,将当前元素设置为上一个已经返回的元素,则可继续返回前一元素。
            return (E) elementData[lastRet = i];
        }

        //设置lastRet位置的元素为元素e.但每次调用set(e)之前,必须先调用next()或previous()方法。否则,抛出异常!
        public void set(E e) {
            if (lastRet < 0) //检测范围
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e); //进行设置操作
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        //在当前元素位置cursor处加入元素e.
        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor; //设置当前位置cursor
                ArrayList.this.add(i, e); //在cursor处加入元素e.
                cursor = i + 1; //设置当前位置为cursor+1,为下一次加入做准备
                lastRet = -1; //保证了在调用add(e)之后,不能调用remove(),set(e)方法。
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /** * 从原始列表中取出一个由fromIndex到toIndex的子列表,并且继承了原始列表的几乎所有方法。 * Returns a view of the portion of this list between the specified * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If * {@code fromIndex} and {@code toIndex} are equal, the returned list is * empty.) The returned list is backed by this list, so non-structural * changes in the returned list are reflected in this list, and vice-versa. * The returned list supports all of the optional list operations. * * <p>This method eliminates the need for explicit range operations (of * the sort that commonly exist for arrays). Any operation that expects * a list can be used as a range operation by passing a subList view * instead of a whole list. For example, the following idiom * removes a range of elements from a list: * <pre> * list.subList(from, to).clear(); * </pre> * Similar idioms may be constructed for {@link #indexOf(Object)} and * {@link #lastIndexOf(Object)}, and all of the algorithms in the * {@link Collections} class can be applied to a subList. * * <p>The semantics of the list returned by this method become undefined if * the backing list (i.e., this list) is <i>structurally modified</i> in * any way other than via the returned list. (Structural modifications are * those that change the size of this list, or otherwise perturb it in such * a fashion that iterations in progress may yield incorrect results.) * * @throws IndexOutOfBoundsException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */
    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)];
                }

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

你可能感兴趣的:(1---collection集合之ArrayList原理分析)