ArrayList构造方法源码分析
首先看一下无参的构造方法:
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData;
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
在未指定容量大小时,会将final的DEFAULTCAPACITY_EMPTY_ELEMENTDATA给elementData,这样的好处是无论多少次实例化无参ArrayList初始的保存对象都是固定的,而不必每次都创建一个新的Object数组.
这样需要在每次做添加操作时调用方法ensureCapacityInternal(int):
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
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.copyOf(elementData, newCapacity);
}
在每次调用添加操作时都会验证是否未指定容量大小的实例化,这里的DEFAULT_CAPACITY=10,也就是说,当不指定容量大小时,第一次添加操作会给list的容量设为10.
提及一下modCount这个属性,它是用作保存对list修改操作的次数。它的值常常用在iterator中,在遍历前会保存它的值,在每次next(),remove()中都回去比较modCount是否改变,改变了就会抛出ConcurrentModificationException.
grow()用于增加list的容量,该方法中第二行也可写成:
int newCapacity = oldCapacity * 3 / 2;
但位运算的速度比乘除的速度要快很多.
有容量参数构造方法显得简单很多:
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);
}
}