ArrayList有三种初始化方式:
1.指定大小初始化 public ArrayList(int initialCapacity)
2.传入一个Collection对象初始化,并将对象中的数据添加到ArrayList中 public ArrayList(Collection<? extends E> c)
3.默认构造函数初始化 public ArrayList()
默认长度:
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
从上面可以看出当使用无参构造函数创建ArrayList时,默认长度为0
调用add方法添加元素时
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}//默认空数组
private int size;//元素个数
transient Object[] elementData;//存放元素的数组
private static final int DEFAULT_CAPACITY = 10;//默认容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//int最大值-8
//添加元素
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//确保内部容量,将元素个数与数组长度比较判断是否扩容
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)//如果最小需要容量大于数组长度,将数组扩容
grow(minCapacity);
}
//计算最小需要容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
//扩容
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//将数组长度的二进制表达形式右移,相当于原来的0.5倍,每次扩容1.5倍
if (newCapacity - minCapacity < 0)//如果新容量小于最小需要容量,则将新容量设置为最小容量
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)//如果新容量大于int最大值减8,则将新容量设置为int类型的最大容量
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
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;
}
从上述代码可以看出,当第一次调用add添加元素时ArrayList才会设置数组默认长度10,之后每超出数组长度就会进行扩容,每次扩容是原来的1.5倍