java 扩容
2018-11-22 本文已影响0人
spraysss
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
实现上可能运行分配的最大字节数组稍微小于Integer.MAX_VALUE
,但是MAX_ARRAY_SIZE
这个值对于所有的JVM来说都是ok的,所以尽量让数组长度不要达到Integer.MAX_VALUE
,除非必须要这么做