首先贴一下ArrayList的部分源码:
jdk1.7版本
// 添加操作
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
modCount++; // 修改次数自增1
// overflow-conscious code
// 需求的容量大于数组的长度时扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
// 扩容操作
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); // 扩容1.5倍
if (newCapacity - minCapacity < 0) // newCapacity容量超过int范围变为负数,此时容量只好自增一个设为minCapacity。
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0) // newCapacity容量比预设的大容量还大时进行超大容量扩容,此时的newCapacity和MAX_ARRAY_SIZE
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
// 超大容量扩容
private static int hugeCapacity(int minCapacity) {
// minCapacity需求的容量超过int的最大值变为负数时抛出异常
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
// 当minCapacity需求的容量超过Max_ARRAY_SIZE时,直接将容量设为INTEGER.MAX_VALUE,否则出于节省容量,将容量设为MAX_ARRAY_SIZE
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
从add()方法的操作流程中我们可以看出扩容的步骤。