每个ArrayList实例都有一个容量,该容量是指来存储列表元素的数组的大小,该容量至少等于列表数组的大小,随着ArrayList的不断添加元素,其容量也在自动增长,自动增长会将原来数组的元素向新的数组进行copy。如果提前预判数据量的大小,可在构造ArrayList时指定其容量。
1.ArrayList每次扩容是原来得1.5倍。
2.数组进行扩容时,会将老数据中得元素重新拷贝一份道新的数组中。
4.创建方式不同,容量不同。
为什么是1.5倍
在grow()方法中调用了newCapacity(最小容量)方法
private Object[] grow(int minCapacity) {
return elementData = Arrays.copyOf(elementData,
newCapacity(minCapacity));
}
而在newCapacity()方法中进行右位移1操作
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
...
}
右位移1大约为乘以0.5
故以上