底层操作机制
-
ArrayList中维护了一个Object类型的数组elementData
transient Object[] element;//transient:表示瞬间、短暂的,表示该数组不能被序列化
当创建ArrayList对象时。如果使用的事无参构造函数,则初始elementData的容量为0,第一次添加则扩容elementData为10,如需再次扩容,则扩容elementData为1.5倍
new ArrayList();
底层源码:
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
private static final int DEFAULT_CAPACITY = 10;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 检查数组大小够不够放
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//如果数组是默认容量的空数组,就将最小的容量大小赋值给 minCapacity
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
//再次判断数组容量
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;//类似于计数器,记录数组被修改的次数
// overflow-conscious code
//如果默认最小容量减去数组容量大于0,说明数组的容量不够存,需要扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
//将初始容量赋值给oldCapacity,作为记录,方便下次扩容,
//(oldCapacity >> 1):除2的意思,
//oldCapacity + (oldCapacity >> 1)按照1.5倍扩容
int oldCapacity = elementData.length;
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
若创建对象时使用的事有参构造函数,则初始elementData容量为指定大小,如需要扩容,则直接扩容elementData的1.5倍
new ArrayList(8);
源码:有残构造
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}