标签:扩容 copy number clone max equals block support 表示
/* 默认初始化是10 */
private static final int DEFAULT_CAPACITY = 10;
?
/* 空数组 */
private static final Object[] EMPTY_ELEMENTDATA = {};
?
/* 用于默认大小空实例的共享空数组实例 */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
?
/* 保存ArrayList数据的数组 */
transient Object[] elementsData;
?
/* ArrayList包含元素个数 */
private int size;
?
/* 构造函数,用户自己传的参数 */
public ArrayList(int initialCapacity){
if(initialCapacity > 0){
this.elementsData = new Object[initialCapacity];
}else if(initialCapacity == 0){
this.elementsData = EMPTY_ELEMENTDATA;
}else{
throw new IllegalArgumentException("非法参数");
}
}
?
/* 默认构造函数,初始化为0,当添加第一个元素的时候,扩容为10 */
public ArrayList(){
this.elementsData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA ;
}
?
/* 必要的话就要扩容,确保它能容纳元素的数量 */
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It‘s already
// supposed to be at default size.
: DEFAULT_CAPACITY;
?
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
/* 判断要不要扩容 */
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
?
// overflow-conscious code
if (minCapacity - elementData.length > 0)
/* 这里是扩容的代码,执行到这里就表示已经开始扩容了 */
grow(minCapacity);
}
?
/* 数组的最大容量 */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
?
/* 这里才是扩容的代码 */
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
/* 将oldCapacity右移一位,相当于oldCapacity/2,位运算性能高,新的容量等于旧容量的1.5倍 */
int newCapacity = oldCapacity + (oldCapacity >> 1);
/* 如果新容量小于最小容量,旧将最小容量赋值给新容量 */
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
/* 新容量不能查过数组承受的最大值 */
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.