Java集合之ArrayList 源码解析

145 阅读4分钟

1. 创建ArrayList

ArrayList<Object> list1 = new ArrayList<>();
ArrayList<Object> list2 = new ArrayList<>(16);
ArrayList<Object> list3 = new ArrayList<>(list2);

ArrayList提供了三个构造方法,创建ArrayList对象除了使用空参构造,还可以传递一个int数值指定初始容量或者传递一个集合。

1.1 空参构造ArrayList()

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

其中DEFAULTCAPACITY_EMPTY_ELEMENTDATA是一个空的Object数组

/**
 * Shared empty array instance used for default sized empty instances. We
 * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
 * first element is added.
 */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

elementData是一个Object数组,定义在类的成员变量,用来存放实际数据,将空的数组赋值给elementData。 在 Java 中,transient 是一个关键字,用于修饰类的成员变量。当一个成员变量被声明为 transient 时,表示该变量不会被序列化,即在对象被写入持久存储(如磁盘文件或数据库)时,这个变量的值不会被保存。在网络传输过程中,包含了 transient Object[] elementData 的ArrayList对象,在序列化和反序列化时需要额外的处理来处理elementData数组的内容

/**
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer. Any
 * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
 * will be expanded to DEFAULT_CAPACITY when the first element is added.
 */
transient Object[] elementData; // non-private to simplify nested class access

1.2 初始化指定集合大小ArrayList(int initialCapacity)

如果初始容量>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) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

1.3 初始化传递集合ArrayList(Collection<? extends E> c)

直接将集合转换为Object数组,赋值给了elementData属性,其中if (elementData.getClass() != Object[].class)判断如果不是object[]则进行一次数组拷贝转换为object[]数组

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

2.添加元素

/**
 * 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;
}
private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

判断集合有没有初始化,没有初始长度就是10,反之长度就是minCapacity

private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}

if (minCapacity - elementData.length > 0)判断长度是否足够,grow方法进行扩容。 ArrayList保存了一个modCount属性,修改集合的操作都会让其自增。如果在遍历的时候modCount被修改,则会抛出异常,产生fail-fast事件

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

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

扩容后的容量为原容量的1.5倍。另外ArrayList无是无限扩容的

/**
 * 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) {
   // 当前容量赋值给oldCapacity 
   int oldCapacity = elementData.length;
      //新容量为老容量的1.5倍。oldCapacity >> 1相当于除以2
   int newCapacity = oldCapacity + (oldCapacity >> 1);
      //如果扩容后还不够,则容量为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:
   elementData = Arrays.copyOf(elementData, newCapacity);
 }

如果扩容后的容量比数组最大容量大,调用hugeCapacity()方法,并将扩容前所需要的最小容量传递的进去。 int的最大值为2的31次方-1,所以说ArrayList的最大容量为2的31次方-1。

private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

我们调用空参构造创建一个ArrayList,并且第一次调用add()方法时会将默认的空数组扩容为一个长度为10的数组。 优点: 1.节约内存 2.避免扩容产生的性能损耗