[源码分析]ArrayList
add
public boolean add(E e) {
//先确保数组容量
ensureCapacityInternal(size + 1);
//直接将值放在size位置
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//如果刚开始为空,并且 容量小于默认容量,则初始化 默认容量 (10)
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
//校验是否需要扩容
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
//一定要修改modCount
modCount++;
// 当容量大于当前元素条数,需要扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// 旧容量
int oldCapacity = elementData.length;
//新容量 = 旧容量 + 旧容量 * 2;
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果新容量还是小于需要的容量大小,则采用传入的minCapacity
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//如果minCapacity太大,还需要修正
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
//最后使用Arrays.copyOf 方法扩容
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
//使用 Integer.MAX_VALUE
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
remove
public E remove(int index) {
rangeCheck(index);
modCount++;
//先获取该索引位置的值
E oldValue = elementData(index);
//找到需要复制的元素个数 a b c d e f (如果要删除 d,索引是3 6 - 3 -1 = 2)
int numMoved = size - index - 1;
//将后边的元素拷贝到被删除的索引的位置
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//最后一位置为 null
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
get
E elementData(int index) {
return (E) elementData[index];
}
多学点,总不会吃亏的。