ArrayList
1、ArrayList源码
1、add方法 先扩容,后赋值
//添加方法
public boolean add(E e) {
//将数组扩容,
ensureCapacityInternal(size + 1);
//将原数组+1的位置 赋值
elementData[size++] = e;
return true;
}
2、扩容方法
private void ensureExplicitCapacity(int minCapacity) {
//操作次数+1
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//扩容
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
//原有数组长度右移一位 比如10 就是 10 + 5
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 重新创建到一个新长度的数组
elementData = Arrays.copyOf(elementData, newCapacity);
}