ArrayList的动态扩容原理
动态扩容方法:add(E e)
源码解析:
ArrayList的部分代码
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
public boolean add(E e) {// 我们刚开始调用的方法add
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {//add所调用的方法
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {第二个调用的
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)//当最小容量比长度还大则扩容
grow(minCapacity);
}
走进 grow(int minCapacity)方法:
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
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);
}
注:最小容量:10 最大容量Integer.MAX_VALUE - 8
先获取老容量的值
新容量=老容量+1/2的老容量(共1.5的老容量)
当新容量比最小容量小时:
* 新容量=最小容量
当新容量大于最大容量时:
- 判断小容量是否为负数,是负数则抛异常
- 判断新容量是否突破了最大值,是则返回size(容量),不扩容
当新容量处于小容量与大容量之间则copyof-》扩容