private void ensureCapacity(int minCapacity) {
// overflow-conscious code
if (minCapacity - buf.length > 0)
grow(minCapacity);
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 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
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = buf.length;
int newCapacity = oldCapacity << 1;
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
buf = Arrays.copyOf(buf, 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;
}
擴容操作理想情況是將容積增加為原來的2倍
newCapacity=Math.max(oldCapacity*2,minCapacity)
確保擴容后的數組大于等于minCapacity
曲初,擴容的意義就是增大容量嘛當
newCapacity
大于MAX_ARRAY_SIZE
体谒,調用hugeCapacity
, 這里對newCapacity
根據minCapacity
做一個微調,如果minCapacity
>MAX_ARRAY_SIZE
,那么newCapacity=Integer.MAX_VALUE
,否則newCapacity=MAX_ARRAY_SIZE
這么做的理由是因為不同的JVM
實現上可能運行分配的最大字節(jié)數組稍微小于Integer.MAX_VALUE
,但是MAX_ARRAY_SIZE
這個值對于所有的JVM來說都是ok的臼婆,所以盡量讓數組長度不要達到Integer.MAX_VALUE
抒痒,除非必須要這么做