源码剖析集合类——ArrayList

此博客用于个人学习,来源于书籍和网上,对知识点进行一个整理。

List 集合的一种典型实现——ArrayList 类:

ArrayList 就是动态数组,它能够动态的增加和减少元素,实现了 ICollection 和 IList 接口以及灵活地设置数组的大小。它是一个用数组实现的集合,支持随机访问,元素有序且可以重复。

1. 字段属性:
//集合的默认大小
private static final int DEFAULT_CAPACITY = 10;

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

//这也是一个空的数组实例,和 EMPTY_ELEMENTDATA 空数组相比是用于了解添加元素时数组膨胀多少
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

/**
 * 存储ArrayList集合的元素,集合的长度即这个数组的长度
 * 1.当 elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA 时将会清空 ArrayList
 * 2.当添加第一个元素时,elementData长度会扩展为DEFAULT_CAPACITY=10
 */
transient Object[] elementData; // non-private to simplify nested class access

//表示集合的长度
private int size;
2. 构造函数:

1)无参构造函数:此时初始容量为0

/**
 * 构造函数:数组的初始容量为0
 * 
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

2)初始化集合大小创建 ArrayList 集合:当大于 0 时,给定多少就创建多大的数组;当等于 0 时,创建一个空数组;当小于 0 时,抛出异常

/**
 *
 * Constructs an empty list with the specified initial capacity.
 *
 * @param  initialCapacity  the initial capacity of the list
 * @throws IllegalArgumentException if the specified initial capacity
 *         is negative
 */
public ArrayList(int initialCapacity) {
    //当大于0时,给定多少就创建多大的数组
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
        //当等于0时,创建一个空数组
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        //当小于0时,抛出异常
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

3)将已有的集合复制到 ArrayList

/**
 * Constructs a list containing the elements of the specified
 * collection, in the order they are returned by the collection's
 * iterator.
 *
 * @param c the collection whose elements are to be placed into this list
 * @throws NullPointerException if the specified collection is null
 */
public ArrayList(Collection<? extends E> 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;
    }
}
3. 添加元素:

ArrayList 集合是数组构成的,那么向 ArrayList 中添加元素,也就是向数组赋值。由于数组的长度是固定的,于是 ArrayList 内部就涉及到数组的扩容。扩容的核心方法就是跳动 Arrays.copyOf 方法,来创建一个更大的数组,然后将原数组的元素拷贝过去即可。

/**
 * 创建一个更大的数组,然后将原数组元素拷贝过去
 *
 * Appends the specified element to the end of this list.
 *
 * @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;
}

在调用 add 方法添加元素之前,首先要调用 ensureCapacityInternal 方法来确定集合的大小,如果集合满了,就要进行扩容操作。下面是依次调用的方法:

/**
 * 这里的minCapacity是集合当前大小
 * elementData是实际用来存储元素的数组,注意数组的大小和集合的大小不是相等的,前面的size是指数组大小
 * @param minCapacity
 */
private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

/**
 * 首先对修改次数modCount加一,这里的modCount给ArrayList的迭代器使用,在并发操作被修改时,提供快速失败行为;
 * 接着判断minCapacity是否大于当前ArrayList内部数组的长度,大于则调用grow方法对内部数组elementData扩容
 * @param minCapacity
 */
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

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

/**
 * 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
 */
private void grow(int minCapacity) {
    // overflow-conscious code
    //得到原始数组的长度
    int oldCapacity = elementData.length;
    //新数组的长度等于原数组长度的1.5倍
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    //当新数组长度仍然比minCapacity小,则为保证最小长度,新数组等于minCapacity
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    //当得到的新数组长度比MAX_ARRAY_SIZE大时,调用hugeCapacity处理最大数组
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    //调用Arrays.of将原数组拷贝到一个大小为newCapacity的新数组(拷贝引用)
    elementData = Arrays.copyOf(elementData, newCapacity);
}

总结一下 ArrayList 集合添加元素:

  • 当通过 ArrayList() 构造一个空集合,初始长度为 0,第一次添加元素,会创建一个长度为 10 的数组,并将该元素赋值到数组的第一个位置
  • 第二次添加元素,集合不为空,而且由于集合的长度 size+1 是小于数组的长度 10,所以直接添加元素到数组的第二个位置,不需要扩容
  • 第 11 次添加元素,此时 size+1=11,而数组长度是 10,这时候创建一个长度为 10+10*0.5 的数组(扩容 1.5 倍),然后将原数组元素引用拷贝到新数组,并将第 11 次添加的元素赋值到新数组下标为 10 的位置
  • 第 Integer.MAX_VALUE-8=2147483639,然后 2147483639%1.5=1431655759(这个数要进行扩容)次添加元素,为了防止溢出,此时会直接创建一个 1431655759+1 大小的数组,这样一直,每次添加一个元素,都只扩大一个范围
  • 第 Integer.MAX_VALUE-7 次添加元素时,创建一个大小为 Integer.MAX_VALUE 的数组,再进行元素添加
  • 第 Integer.MAX_VALUE+1 次添加元素时,抛出 OutOfMemoryError 异常
4. 删除元素:

1)根据索引删除元素:

首先判断给定索引的范围,超过集合大小则抛出异常,然后通过 System.arraycopy 对数组进行自身拷贝

/**
 * 删除索引index处的元素
 *
 * 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,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work

    return oldValue;
}

2)直接删除指定元素:

删除第一次出现的该元素,然后通过 System.arraycopy 对数组进行自身拷贝

/**
 * 删除第一次出现的元素
 *
 * 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
 * <tt>i</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
 * (if such an element exists).  Returns <tt>true</tt> if this list
 * contained the specified element (or equivalently, if this list
 * changed as a result of the call).
 *
 * @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;
}
5. 修改元素:

通过调用 set(int index,E element) 方法将指定索引的 index 处的元素替换成 element,并返回原数组的元素

/**
 * 将指定索引index处的元素替换为element,并返回原数组的元素
 *
 * 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);
    //将指定索引处的元素替换为element
    elementData[index] = element;
    //返回原数组索引长度
    return oldValue;
}
6. 查找元素:

1)根据索引查找元素:首先判断给定索引的合理性,然后直接返回处于该下标位置的数组元素

/**
 * 根据索引查找元素
 *
 * 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);
}

2)根据元素查找索引:

/**
 * 返回第一次出现该元素的下标,如果没有则返回-1
 *
 * Returns the index of the first occurrence of the specified element
 * in this list, or -1 if this list does not contain the element.
 * More formally, returns the lowest index <tt>i</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
 * or -1 if there is no such index.
 */
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;
}
7. 迭代器:

1)iterator:

/**
 * 返回一个Itr对象,是ArrayList的内部类
 *
 * Returns an iterator over the elements in this list in proper sequence.
 *
 * <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();
}

查看内部类 Itr 的源码:

/**
 * An optimized version of AbstractList.Itr
 */
private class Itr implements Iterator<E> {
    //游标,下一个要返回的元素的索引
    int cursor;       // index of next element to return
    //返回最后一个元素的索引,如果没有返回-1
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    Itr() {}

    //通过cursor != size判断是否还有下一个元素
    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;
        //返回索引为i处的元素,并将lastRet赋值为i
        return (E) elementData[lastRet = i];
    }

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

        try {
            //调用ArrayList的remove方法删除元素
            ArrayList.this.remove(lastRet);
            //游标指向删除元素的位置,本来是lastRet+1,这里删除一个元素,然后游标就不变了
            cursor = lastRet;
            //恢复默认值-1
            lastRet = -1;
            //expectedModCount值和modCount同步,因为进行add和remove操作,modCount会加1
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * 便于进行forEach循环
     * @param consumer
     */
    @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();
    }

    /**
     * 前面在新增元素add()和删除元素remove()时,可以看到modCount++,修改set()是不会出现的
     * 即不能在迭代器进行元素迭代时进行增加和删除操作,否则抛出异常
     */
    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

在进行 next() 方法调用的时候,会进行 checkForComodification() 调用,该方法标识迭代器进行元素迭代时,如果同时进行增加和删除操作,会抛出 ConcurrentModificationException 异常,解决方法就是不调用 ArrayList.remove() 方法,转而调用迭代器的 remove() 方法。

2)迭代器 ListIterator:

相比于 Iterator 迭代器,这里的 ListIterator 多出了能向前迭代以及能够新增元素的功能。

/**
 * Returns a list iterator over the elements in this list (in proper
 * sequence).
 *
 * <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);
}

这里的 ListItr 也是一个内部类

/**
 * 内部类ListItr继承了另一个内部类Itr
 *
 * An optimized version of 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();
        }
    }

    //相比于迭代器Iterator,这里多了一个新增操作
    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();
        }
    }
}
8. 其他方法:

1)size():返回集合的长度,一般是指元素的数量

/**
 * 返回集合的长度,也就是元素的数量
 *
 * Returns the number of elements in this list.
 *
 * @return the number of elements in this list
 */
public int size() {
    return size;
}

2)isEmpty():判断集合是否为空

/**
 * 判断集合是否为空
 *
 * Returns <tt>true</tt> if this list contains no elements.
 *
 * @return <tt>true</tt> if this list contains no elements
 */
public boolean isEmpty() {
    return size == 0;
}

3)trimToSize():用于回收多余的内存,一旦确定集合不再添加多余的元素之后,调用该方法将实现集合的数组大小刚好调整为集合元素的大小

/**
 * 回收多余的内存:一旦确定集合不在添加多余的元素之后,该方法将实现集合的数组大小刚好为调整为集合元素的大小
 *
 * Trims the capacity of this <tt>ArrayList</tt> instance to be the
 * list's current size.  An application can use this operation to minimize
 * the storage of an <tt>ArrayList</tt> instance.
 */
public void trimToSize() {
    modCount++;
    if (size < elementData.length) {
        elementData = (size == 0)
          ? EMPTY_ELEMENTDATA
          : Arrays.copyOf(elementData, size);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值