ArrayList
的扩容机制
ArrayList
是实现了List的接口的类,底层数据结构是一个数组,但是该数组实现了可变大小,具备了更好的性能。
那么Arraylist
是如何实现可变大小的呢,一起深入源码看一下。
首先看一下它的几个属性
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
这是ArrayList
类的属性,通过翻译意思我们能够知道DEFAULT_CAPACITY
是数组的默认长度,EMPTY_ELEMENTDATA
是一个空的数组,DEFAULTCAPACITY_EMPTY_ELEMENTDATA
是一个默认的空数组,elementData
是数组缓存区,size
是ArrayList
的元素个数。
ArrayList
的三个构造器
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
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);
}
}
指定初始化容量的大小,返回一个指定大小的数组,为0时返回EMPTY_ELEMENTDATA
。
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
无参构造,返回默认空数组。默认大小为10。
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
Object[] a = c.toArray();
if ((size = a.length) != 0) {
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, size, Object[].class);
}
} else {
// replace with empty array.
elementData = EMPTY_ELEMENTDATA;
}
}
初始化时传入特定集合的元素,底层将其转换为数字,并将其复制给elementDate
;传入集合为空时返回EMPTY_ELEMENTDATA
。
扩容
当向ArrayList
添加元素时,触发扩容机制。
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
/**
* This helper method split out from add(E) to keep method
* bytecode size under 35 (the -XX:MaxInlineSize default value),
* which helps when add(E) is called in a C1-compiled loop.
*/
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
size = s + 1;
}
首先判断size
是否和elementData.length
相等,相等则调用grow()
扩容。
private Object[] grow() {
return grow(size + 1);
}
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
* @throws OutOfMemoryError if minCapacity is less than zero
*/
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
int newCapacity = ArraysSupport.newLength(oldCapacity,
minCapacity - oldCapacity, /* minimum growth */
oldCapacity >> 1 /* preferred growth */);
return elementData = Arrays.copyOf(elementData, newCapacity);
} else {
return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
}
}
如果此时数组是DEFAULTCAPACITY_EMPTY_ELEMENTDATA
,这是无参构造返回的数组。则返回Math.max(DEFAULT_CAPACITY, minCapacity)
,因为minCapacity
此时是1,所以返回默认大小DEFAULT_CAPACITY 值为10。
如果不是无参构造则调用ArraysSupport.newLength()
进行扩容,至此扩容才算真正开始,其中prefGrowth
为 oldCapacity >> 1
,,右移1位即除以2,增长量为oldCapacity
的0.5
public static int newLength(int oldLength, int minGrowth, int prefGrowth) {
// preconditions not checked because of inlining
// assert oldLength >= 0
// assert minGrowth > 0
int prefLength = oldLength + Math.max(minGrowth, prefGrowth); // might overflow
if (0 < prefLength && prefLength <= SOFT_MAX_ARRAY_LENGTH) {
return prefLength;
} else {
// put code cold in a separate method
return hugeLength(oldLength, minGrowth);
}
}
private static int hugeLength(int oldLength, int minGrowth) {
int minLength = oldLength + minGrowth;
if (minLength < 0) { // overflow
throw new OutOfMemoryError(
"Required array length " + oldLength + " + " + minGrowth + " is too large");
} else if (minLength <= SOFT_MAX_ARRAY_LENGTH) {
return SOFT_MAX_ARRAY_LENGTH;
} else {
return minLength;
}
}
int prefLength = oldLength + Math.max(minGrowth, prefGrowth); // might overflow
这句会判断最小增长量和0.5倍增长量取最大值,这里可能会整型溢出。
若溢出则执行hugeLength()
最后通过Arrays.copyOf(elementData, newCapacity);
将原来数据复制到扩容后的数组中。 elementData[s] = e;
将新加入元素添加至数组中。