部分重要屬性
//存放元素的數組
transient Object[] elementData;
//大小,非elementData的length,存入元素的總個數
private int size;
add方法
public boolean add(E e) {
//保證數組不溢出,否則進行擴容操作
ensureCapacityInternal(size + 1);
elementData[size++] = e;
//返回值都爲true
return true;
}
擴容grow方法
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
//擴容大小爲之前的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//新的容量大小不能超過Integer.MAX_VALUE - 8
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//元素複製,主要採用System.arraycopy方法
elementData = Arrays.copyOf(elementData, newCapacity);
}
remove方法
public E remove(int index) {
rangeCheck(index);
modCount++;
//返回舊元素
E oldValue = elementData(index);
int numMoved = size - index - 1;
//如果非末尾元素,所有元素前移
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null;
return oldValue;
}
iterator()方法
public Iterator<E> iterator() {
//訪問指針的封裝對象
return new Itr();
}
private class Itr implements Iterator<E> {
int cursor; // 移動指針
int lastRet = -1; // 上一個指針
int expectedModCount = modCount;
}
總結
- ArrayList採用Object數組存儲元素;
- ArrayList默認容量大小爲10,Object數組採用延遲初始化的方式;
- ArrayList擴容新容量爲原容量的1.5倍;
- iterator原理類似指針,通過cursor值來訪問修改數組元素;