Default initial capacity.

private static final int DEFAULT_CAPACITY = 10;

Shared empty array instance used for empty instances.

private static final Object[] EMPTY_ELEMENTDATA = {};

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

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; 

detail(explanation): non-private to simplify nested class access

The size of the ArrayList (the number of elements it contains).

private int size;

jdk 1.8 Arraylist 扩容机制

  1. ArrayList中维护了一个Object类型的数组elementData. transient Object[] elementData; transient表示瞬间,短暂的,表示该属性不会被序列化==
  2. 当创建ArrayList对象时,如果使用的是无参构造器,则初始elementData容量为0,第1次添加,则扩容elementData为10,如需要再次扩容,则扩容elementData为1.5倍。
  3. 如果使用的是指定大小的构造器,则初始elementData容量为指定大小,如果需要扩容,则直接扩容elementData为1.5倍。
ArrayList list = new ArrayList();
//ArrayList list = new ArrayList(8);
//使用for给list集合添加 1-10数据
for (int i = 1; i <= 10; i++) {
		list.add(i);
}
//使用for给list集合添加 11-15数据
for (int i = 11; i <= 15; i++) {
		list.add(i);
}
list.add(100);
list.add(200);
list.add(null);

先创建默认大小

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
 
 
public ArrayList() {  
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; // 默认创建一个空的数组
}

执行add 方法

  1. 先确定是否要扩容 ensureCapacityInternal
  2. 给 size所在的索引加1,然后在执行赋值
public boolean add(E e) {
		ensureCapacityInternal(size + 1);  // Increments modCount!!
		elementData[size++] = e;
		return true;
}