2.ArrayList源码解析

62 阅读4分钟

一、ArrayList类图总览

image.png

ArrayList实现List、Serializable、RandomAccess、Cloneable四个接口。

List:中提供了集合的添加、删除、修改、迭代遍历等基本功能

RandomAccess:表示ArrayList支持快速的随机访问

Serializable:表示ArrayList支持序列化相关功能

Cloneable:表示ArrayList支持克隆

二、属性

Image.png

Object[] elementData:该数组用来存储Object对象,添加新元素时如果数组长度不够,创建新数据并将原数组 元素拷贝至新数组。

size:表示该数组元素大小,数组中已存储元素的数量即图中红色部分。白色部分数组中未使用数量

三、构造函数

ArrayList有三个构造函数,我们来一一介绍

1.无参构造函数ArrayList()

/**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

平时使用最多的一个构造函数,会给elementData赋值到一个空数组。在首次添加元素时扩容为一个容量为10的数组。

2.ArrayList(int initialCapacity)

/**
 * 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 时,创建 Object 数组
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    // 初始化容量等于 0 时,使用 EMPTY_ELEMENTDATA 对象
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    // 初始化容量小于 0 时,抛出 IllegalArgumentException 异常
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

该构造方法根据传入的初始化容量创建ArrayList数组。如果我们使用时预先知道数组大小,建议使用该构造方法,可避免数组扩容造成的性能浪费,提升系统性能。

3.ArrayList(Collection<? extends E> c)

/**
 * 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) {
    // 将 c 转换成 Object 数组
    elementData = c.toArray();
    // 如果数组大小大于 0
    if ((size = elementData.length) != 0) {
        // defend against c.toArray (incorrectly) not returning Object[]
        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
        // 如果集合元素不是 Object[] 类型,则会创建新的 Object[] 数组,并将 elementData 赋值到其中,最后赋值给 elementData 。
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    // 如果数组大小等于 0 ,则使用 EMPTY_ELEMENTDATA 。
    } else {
        // replace with empty array.
        this.elementData = EMPTY_ELEMENTDATA;
    }
}

将传入的集合调用toArray()方法赋值给elementData

四、add()方法添加单个元素

/**
 * Appends the specified element to the end of this list.
 *
 * @param e element to be appended to this list
 * @return {@code true} (as specified by {@link Collection#add})
 */
@Override
public boolean add(E e) {
    // 增加数组修改次数
    modCount++;
    // 添加元素
    add(e, elementData, size);
    // 返回添加成功
    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);
    // 增加数组修改次数
    modCount++;
    // 如果数组大小不够,进行扩容
    final int s;
    Object[] elementData;
    if ((s = size) == (elementData = this.elementData).length)
        elementData = grow();
    // 将 index + 1 位置开始的元素,进行往后挪
    System.arraycopy(elementData, index,
                     elementData, index + 1,
                     s - index);
    // 设置到指定位置
    elementData[index] = element;
    // 数组大小加一
    size = s + 1;
}

这里我们主要分析add(int index, E element)方法

1.校验位置是否在数组范围内,如果index>size || index < 0抛出异常

2.增加数组修改次数,对modeCount进行+1操作

3.判断数组大小是否充足进行扩容。如果size==elementData.length调用grow()方法进行扩容

4.调用System.arraycopy()方法进行复制,将index+1位置开始的元素依次向后挪动。

五、grow()方法扩容

/**
 * 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
 * @throws OutOfMemoryError if minCapacity is less than zero
 */
private Object[] grow(int minCapacity) {
    int oldCapacity = elementData.length;
    // 如果原容量大于 0 ,或者数组不是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 时,计算新的数组大小,并创建扩容
    if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        int newCapacity = ArraysSupport.newLength(oldCapacity,
                minCapacity - oldCapacity, /* minimum growth */
                oldCapacity >> 1           /* preferred growth */);
        return elementData = Arrays.copyOf(elementData, newCapacity);
    // 如果是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 数组,直接创建新的数组即可。
    } else {
        return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
    }
}

private Object[] grow() {
    return grow(size + 1);
}

在第四步中调用grow方法,下面来看下grow()方法到底做了些什么?

1.调用grow(size + 1)方法,将当前size+1作为参数传入并调用grow方法

2.判断原容量>0或数组不是DEFAULTCAPACITY_EMPTY_ELEMENTDATA时计算新数组大小,创建扩容

3.调用ArraysSupport.newLength(int oldLength, int minGrowth, int prefGrowth)方法获取新容量的大小,可以简单理解为Math.max(minGrowth, prefGrowth) + oldLength。一般情况下oldCapacity 》1为右移操作(相当于除以2),是1.5倍扩容

4.调用Arrays.copyOf()方法拷贝一个新数组,根据新的容量大小创建数组并将原数组中的元素拷贝至新数组,将引用指向新创建的数组

总结:

1.ArrayList是基于数组实现的List实现类支持在数组容量不够是时按照1.5倍自动扩容。同时支持手动扩容,手动缩容

2.ArrayList随机访问时间复杂度是O(1),如果想要查询指定元素平均时间复杂度是O(n)

3.ArrayList底层是数组,随机访问时间复杂度是O(1),而在插入删除时伴随着数组的复制,效率很低。