简单的ArrayList,一句话概括“初始化空数组,每次加元素右移一位”
作者:互联网
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);
}
标签:右移,初始化,int,ArrayList,elementData,newCapacity,minCapacity,数组,oldCapacity 来源: https://blog.csdn.net/qq_38384460/article/details/112920555