无参构造器初始化
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//初始化,将elementData变量设置成一个空对象数组
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
调用add方法
//ensureCapacityInternal 确定当前的容量
public boolean add(E e) {
//确认容量值
ensureCapacityInternal(size + 1);
//后++先操作,再++
elementData[size++] = e;
return true;
}
调用ensureCapacityInternal方法
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
调用calculateCapacity方法
private static final int DEFAULT_CAPACITY = 10;
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//先判断elementData是否是空数组
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//返回默认值10和minCapacity中最大的值
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
//返回最小容量
return minCapacity;
}
调用ensureExplicitCapacity方法
private void ensureExplicitCapacity(int minCapacity) {
//记录集合被修改的次数
modCount++;
// 判断最小的容量和实际容量的大小值
// 假如实际容量的值小于最小的容易,则开始正式的扩容
// 将最小的容量值作为参数值
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
调用grow方法
private void grow(int minCapacity) {
//获取到当前实际的容量值
int oldCapacity = elementData.length;
//将新的容量值 x 1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//当新的扩容值,依然小于最小容量值的时候,将最小容量值赋值给新容量值
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//将elementData 进行数组copy,容量就是新的容量值
elementData = Arrays.copyOf(elementData, newCapacity);
}