Arraylist的最大长度
- Arraylist的MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
- Arraylist的最大长度为2147483647即2^31-1
Arraylist的MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
最近在学习java的基础知识,学到集合的时候,在查看ArrayList的源码的时候,发现了一个有趣的东西。ArrayList集合的最大长度是多少。
/**
* 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 = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, 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;
}
源码中定义MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;上面的注释也写明白了。一些vm可能会在数组中保留一些header信息,分配更大的长度可能会导致OutOfMemoryError异常。
这里这样做的原因是为了尽可能的避免因为vm使用了数据保存header的信息而导致分配更大的长度产生OutOfMemoryError异常。但是并不一定超出这个长度一定会异常。这只是为了尽可能的去避免。但是假使当一个vm使用了数组保存一些header,并且这些header使用的长度大于8时那么当数组扩容到2^31-1再减去header的信息长度时依旧会发生OutOfMemoryError异常。
Arraylist的最大长度为2147483647即2^31-1
arrayList的底层结构是基于数组实现的,作为下标的最大数据应该是Integer.MAX_VALUE即2^31-1。我们观察上面代码中的grow(int minCapacity)会发现其中有一个特殊的地方
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
而hugeCapacity(int minCapacity)方法中表明了,
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
新长度在满足一定条件时是可以为Integer.MAX_VALUE的。所以说Arraylist的最大长度为2147483647即2^31-1。