ArrayListJava中的最大容量是多少?由于ArrayList在内部使用数组,它的容量将是Integer.MAX_VALUE,对吗?
此代码显示的最大容量ArrayList为Integer.MAX_VALUE:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
/**
* The maximum size of array to allocate (unless necessary).
* 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;
}
Run Code Online (Sandbox Code Playgroud)
然而,当我这样做时new ArrayList<>(Integer.MAX_VALUE),会发出以下错误:
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
Run Code Online (Sandbox Code Playgroud)
此代码显示的最大容量
ArrayList为Integer.MAX_VALUE:
不,它没有。它显示最大容量为:
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
Run Code Online (Sandbox Code Playgroud)
请注意8从 的值中减去Integer.MAX_VALUE。另外,请记住,这只是假设内存充足的最大容量。如果 JVM 没有足够的可用内存来分配必要的数组,则可能会为较小的容量抛出 OOME。
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |