部分ArrayList源码

package com.seaxll.collections;

import sun.misc.SharedSecrets;

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

/**
 * ClassName: ArrayList
 * Description:
 * date: 2019/11/22 22:02
 *
 * @author seaxll
 * @since JDK 1.8
 */
public class ArrayList extends AbstractList
        implements List, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

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

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

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

    /**
     * 存储ArrayList元素的数组缓冲区。ArrayList的容量是此数组缓冲区的长度。
     * 当添加第一个元素时,任何elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * 的空ArrayList都将被扩展为DEFAULT_CAPACITY(默认容量)
     *
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * size: ArrayList中实际元素的个数,并有:size <= elementData.length
     * 因为 elementData 是容纳 ArrayList 的容器,
     * size > elementData.length就越界了,需要扩容
     * @serial
     */
    private int size;

    /**
     *  构造具有指定初始容量的空列表
     *
     *  @param  initialCapacity 指定的初始容量
     *  @throws IllegalArgumentException 容量小于0 抛出非法参数异常
     */
    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);
        }
    }

    /**
     * 构造初始容量为10的空列表:
     *  开始只是 使用 空实例 DEFAULTCAPACITY_EMPTY_ELEMENTDATA({}) 创建,
     *  在add第一个元素的时候才会真正给elementData分配一个默认大小的素数组空间。
     *  默认大小 DEFAULT_CAPACITY 的值为 10
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 通过集合构造一个新的 ArrayList ,这个 ArrayList 包含指定集合中的所有元素。
     *
     * @param c 要将其元素放入此列表中的集合
     * @throws NullPointerException 如果集合为空,抛出空指针异常
     */
    public ArrayList(Collection c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * 将此ArrayList实例的容量修剪为列表的当前大小。
     * 程序可以使用此操作最小化ArrayList实例的存储。
     *
     * 注意:这里只是根据size的大小去除elementData中的空元素,而不是通过判断 == null 去掉null的元素:
     *  1) 通过remove(int index)方法(删除index位置,并将index后的元素前移),在后面移动空出的位置会被 剪切 掉
     *  2) 如果通过set()方法将某个索引的位置(不论是在中间还是末尾)为null,其size不变,并不会被移出
     *  3) 此外,trimToSize还会剪切扩容后(或初始化ArrayList容量时)多出的空余位置。
     */
    public void trimToSize() {
        // modCount:继承自 AbstractList 中的属性,记录着 ArrayList 被修改的次数
        // modCount 与 fail-fast 机制有关 (concurrentModficationException)
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
                    ? EMPTY_ELEMENTDATA
                    : Arrays.copyOf(elementData, size);
        }
    }

     /**
     * Increases the capacity of this ArrayList instance, if
     * necessary, to ensure that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     * 如有必要,增加此 ArrayList 实例的容量,以确保由最小容量参数指定。
     * @param   minCapacity   the desired minimum capacity
     *          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) { //minCapacity > minExpand 则设置
            ensureExplicitCapacity(minCapacity);
        }
    }
    //确保集合内部的容量
     private void ensureCapacityInternal(int minCapacity) {
        if (elementData == EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

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

     /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     *一些虚拟机保留数组中的一些标题字。 
     *尝试分配较大的数组可能会导致OutOfMemoryError:请求的数组大小超过VM限制
     * 注:怕超过VM限制,所以只用 Integer.MAX_VALUE - 8  设置MAX_ARRAY_SIZE的值!
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     * 增加容量以确保它至少可以容纳由最小容量参数指定的元素数。
     * @param minCapacity the desired minimum capacity
     *        minCapacity  所需的最小容量
     */
    private void grow(int minCapacity) {
        // overflow-conscious code 溢出-察觉代码
        int oldCapacity = elementData.length; //旧的容量大小
        int newCapacity = oldCapacity + (oldCapacity >> 1); //oldCapacity >> 1 : >> 右移 相当于 oldCapacity/2
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);//看下面的hugeCapacity()方法,数组的最大容量不会超过MAX_ARRAY_SIZE
        // minCapacity is usually close to size, so this is a win:
        // minCapacity通常接近于大小,所以这是一个win:

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

    /**
     * Returns the number of elements in this list.
     * 返回此列表中的元素数。获取集合的大小
     *
     * @return the number of elements in this list
     *         此列表中的元素数
     */
    public int size() {
        return size;
    }

    /**
     * Returns true if this list contains no elements.
     * 判断是否为空,如果集合为没有包含任何元素,返回 true !
     * @return true if this list contains no elements
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     *如果此列表包含指定的元素,则返回true。 更正式地,
     *当且仅当这个列表包含至少一个元素e使得(o == null?e == *null:o.equals(e))时,
     *返回true。
     * @param o element whose presence in this list is to be tested
     * @return true if this list contains the specified element
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     *返回此列表中指定元素的第一次出现的索引,如果此列表不包含元素,
     *则返回-1。 更正式地,返回最低索引i,使得(o == null?get(i)== null:o.equals(get(i))),
     *或-1,如果没有这样的索引。
     * 
     *返回:此列表中指定元素的第一次出现的索引,如果此列表不包含元素,则为-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;
    }

    /**
     * 返回此列表中指定元素的最后一次出现的索引,如果此列表不包含元素,
     *则返回-1。 更正式地,返回最高索引i,使得(o == null?get(i)== null:o.equals(get(i))),
     *或-1如果没有这样的索引。
     *
     *返回:此列表中指定元素的最后一次出现的索引,如果此列表不包含元素,则为-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;
    }


    /**
     * Returns a shallow copy of this ArrayList instance.  (The
     * elements themselves are not copied.)
     * 返回此 ArrayList 实例的浅拷贝。 (元素本身不被复制。) 
     * @return a clone of this ArrayList instance
     */
    public Object clone() { //实现了Cloneable接口,覆盖了函数clone(),能被克隆。
        try {
            @SuppressWarnings("unchecked")
                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();
        }
    }

     /**
     * 以正确的顺序返回包含此列表中所有元素的数组(从第一个元素到最后一个元素)。
     *
     * 

This method acts as bridge between array-based and collection-based * APIs. * 此方法充当基于阵列和基于集合的API之间的桥梁 * @return an array containing all of the elements in this list in * proper sequence * 一个包含正确顺序的列表中所有元素的数组 */ public Object[] toArray() { return Arrays.copyOf(elementData, size);//使用Arrays工具类 } /** * Returns the element at the specified position in this list. * 返回此列表中指定位置的元素。 * * @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); return elementData(index); } /** * Replaces the element at the specified position in this list with * the specified element. * 用指定的元素替换此列表中指定位置处的元素。 * * @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; } /** * Appends the specified element to the end of this list. * 将指定的元素追加到此列表的末尾。 * @param e element to be appended to this list * @return true (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! 增加modCount!用于判断 elementData[size++] = e; return true; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * 在此列表中指定的位置插入指定的元素。 将当前在该位置的元素(如果有) * 和任何后续元素向右移(将一个添加到它们的索引)。 * @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++; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * 删除此列表中指定位置的元素。 将任何后续元素向左移(从它们的索引中减去一个)。 * @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, //public static native void arraycopy(Object src, int srcPos, // Object dest, int destPos,int length); //调用了本地的方法 : 将指定源数组的数组从指定位置开始复制到目标数组的指定位置。 elementData[--size] = null; // clear to let GC do its work 设置为 null ,让gc去回收 return oldValue; } /** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * 从列表中删除指定元素的第一次出现(如果存在)。 *如果列表不包含元素,则不会更改。 更正式地,删除具有最低索引i的元素,使得(如果这样的元素存在) *(o == null?get(i)== *null:o.equals(get(i)))。 *如果此列表包含指定的元素(或等效地,如果此列表作为调用的结果更改),则返回true。 * * @param o element to be removed from this list, if present * @return true if this list contained the specified element 如果包含返回 true */ 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) { 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 } /** * Removes all of the elements from this list. The list will * be empty after this call returns. *从此列表中删除所有元素。 此调用返回后,列表将为空 */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** * 将指定集合中的所有元素以指定集合的Iterator返回的顺序追加到此列表的末尾。 *如果在操作正在进行时修改指定的集合,则此操作的行为是未定义的。 *(这意味着如果指定的集合是此列表,则此调用的行为是未定义的,并且此列表不是空的。) * @param c collection containing elements to be added to this list * @return true if this list changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean addAll(Collection 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; } /* *将指定集合中的所有元素插入到此列表中,从指定位置开始。 * */ public boolean addAll(int index, Collection c) { rangeCheckForAdd(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount int numMoved = size - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } /** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). *从此列表中删除其索引在fromIndex(包含)和toIndex(排除)之间的所有元素。 *将任何后续元素向左移(减少其索引)。 */ protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // clear to let GC do its work int newSize = size - (toIndex-fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; } size = newSize; } /** * 检查给定的索引是否在范围内。 如果没有,则抛出一个适当的运行时异常。 * 私有方法 */ private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * A version of rangeCheck used by add and addAll. * 由add和addAll使用的rangeCheck的版本。 * 私有方法 */ private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * Removes from this list all of its elements that are contained in the * specified collection. * 从此列表中删除包含在指定集合中的所有元素。 * @param c collection containing elements to be removed from this list * @return {@code true} if this list changed as a result of the call * 如果此列表由于调用而更改 则返回true */ public boolean removeAll(Collection c) { return batchRemove(c, false); } /** * Retains only the elements in this list that are contained in the * specified collection. In other words, removes from this list all * of its elements that are not contained in the specified collection. *仅保留此列表中包含在指定集合中的元素。 换句话说, *从此列表中删除未包含在指定集合中的所有元素。 * @param c collection containing elements to be retained in this list * @return {@code true} if this list changed as a result of the call * 如果此列表由于调用而更改 则返回true */ public boolean retainAll(Collection c) { return batchRemove(c, true); } //批量移除 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]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. //保留与AbstractCollection的行为兼容性,即使c.contains()抛出。 if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; } /** * 将ArrayList实例的状态保存到流(即,序列化它)。 */ 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; iArrayList instance from a stream (that is, * deserialize it). *从流重构 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 listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** * Returns a list iterator over the elements in this list (in proper * sequence). *返回此列表中的元素(按正确顺序)的列表迭代器。 *

The returned list iterator is fail-fast. *返回的列表迭代器是fail-fast的。 * @see #listIterator(int) */ public ListIterator listIterator() { return new ListItr(0); } /** * Returns an iterator over the elements in this list in proper sequence. *以正确的顺序返回此列表中的元素的迭代器。 *

The returned iterator is fail-fast. *返回的列表迭代器是fail-fast的。 * @return an iterator over the elements in this list in proper sequence */ public Iterator iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr * AbstractList.Itr的优化版本 */ private class Itr implements Iterator { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such 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(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /** * An optimized version of AbstractList.ListItr * AbstractList.ListItr的优化版本 */ private class Itr implements Iterator { int cursor; // index of next element to return //下一个元素的游标 int lastRet = -1; // index of last element returned; -1 if no such //上一个元素的 int expectedModCount = modCount; //修改计数器期望值 public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; //此时的游标,指向的是本次要遍历的对象,因为上一次已经++了,初始值为0,没有++的情况下是第一个元素 if (i >= size) //越界了 throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; //游标指向了下一个元素, 但 i 的值没有变 return (E) elementData[lastRet = i]; //将 i 赋值给lastRet,取的值是方法开始时int i=cursor;中的cursor指向的值,而且最终这个游标的数值赋值给了lastRet } public void remove() { if (lastRet < 0) // 如果没有next()操作就直接remove的话,lastRet=-1,会抛异常 throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); // remove之前,cursor、lastRet的值没有修改,都是上次next之后的值,因此此处的lastRet指向上次next获取的元素 cursor = lastRet; lastRet = -1; expectedModCount = modCount; // 手动将ArrayList.remove()后modCount的值赋给expectedModCount,避免引起不一致 } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer 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(); } } //subList 以及后面的代码不在做分析,实际情况中很少用到,需要的时候,请自行看源码分析 }

你可能感兴趣的:(部分ArrayList源码)