ArrayList的最大容量是多少? [英] What is the max capacity of an ArrayList?
问题描述
我知道ArrayList的初始容量为10.超过此限制后,将创建一个新的ArrayList,容量为(oldcapacity * 3 / 2) + 1
,然后将元素复制过来.
I know that the initial capacity of an ArrayList is 10. When this limit is exceeded, a new ArrayList is created with the capacity of (oldcapacity * 3 / 2) + 1
, and the elements are copied over.
但是ArrayList的最大容量是多少?
But what is the maximum capacity of an ArrayList?
在一次采访中有人问我这个问题.采访者对默认的初始容量不感兴趣,但想知道ArrayList的最大容量.
I was asked this question in an interview. The interviewer was not interested in the default initial capacity, but wanted to know the maximum capacity of an ArrayList.
推荐答案
查看源代码:
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
,您将在此处看到相关部分:
and you will see the relevant part here:
this.elementData = new Object[initialCapacity];
所以数组列表最多可以包含一个数组可以容纳的元素.
so the array list can at most so many elements as an array can hold.
可能会出现下一个问题: 多少个元素可以容纳一个数组?
the next question may arise: how many elements can hold an array?
答案是:这取决于您正在编写什么VM:
the answer is: it depends on what VM are you writing the code:
在JDK8中:
/**
* 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;
其中
/**
* A constant holding the maximum value an {@code int} can
* have, 2<sup>31</sup>-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff;
这篇关于ArrayList的最大容量是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!