jdk1.2
The expansion algorithm is like this.1.5倍+1
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
elementData = new Object[newCapacity];
System.arraycopy(oldData, 0, elementData, 0, size);
}
}
jdk1.3
And jdk1.2
the same expansion mechanism
jdk1.4
And jdk1.2
the same expansion mechanism
jdk1.5
And jdk1.2
the same expansion mechanism
jdk1.6
And jdk1.2
the same expansion mechanism, but new ways
Arrays.copyOf( elementData , newCapacity );
to copy new array
jdk1.7
This version ArrayList
has changed. The
expansion mechanism uses a right shift equivalent to divide by 2, and there is no +1 operation, which is 1.5 times the original length.
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); //这里直接是1.5倍,没有和一起一样进行+1
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
jdk1.8
Same jdk1.7
as
jdk9
The code has changed a little bit but basically unchanged
jdk10
Not much changed
jdk11
The code is more concise, but there is not much change as before
jdk12
Same as before
jdk13
When it should be used to ArraysSupport.newLength
get the new array length
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)];
}
}
jdk14
Same as jdk13