1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
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) {//minCapacity=size + 1
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)];
}
}
/*
Calculates a new array length given an array's current length, a preferred
* growth value, and a minimum growth value. If the preferred growth value
* is less than the minimum growth value, the minimum growth value is used in
* its place. If the sum of the current length and the preferred growth
* value does not exceed {@link #MAX_ARRAY_LENGTH}, that sum is returned.
* If the sum of the current length and the minimum growth value does not
* exceed {@code MAX_ARRAY_LENGTH}, then {@code MAX_ARRAY_LENGTH} is returned.
* If the sum does not overflow an int, then {@code Integer.MAX_VALUE} is
* returned. Otherwise, {@code OutOfMemoryError} is thrown.
*/
public static int newLength(int oldLength, int minGrowth, int prefGrowth) {
// assert oldLength >= 0
// assert minGrowth > 0
/*
假设此时list容量为10,元素为10,要再添加一个元素,
oldLength=10
minGrowth=11-10=1
prefGrowth=10>>1=5
所以newLength = Math.max(minGrowth, prefGrowth) + oldLength=Math.max(1, 5) + 10=15
*/
int newLength = Math.max(minGrowth, prefGrowth) + oldLength;//扩容的计算方式
if (newLength - MAX_ARRAY_LENGTH <= 0) {
return newLength;
}
return hugeLength(oldLength, minGrowth);
}
|