gpt4 book ai didi

java - 为什么 ArrayList 的最大数组大小是 Integer.MAX_VALUE - 8?

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:10 24 4
gpt4 key购买 nike

我正在研究 ArrayList 的 Java 8 文档。我知道最大数组大小定义为 Integer.MAX_VALUE - 8 表示 2^31 – 8 = 2 147 483 639。然后重点说了为什么要减8或者为什么不能小于8或者大于8要减?

/**
* 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;

我得到了一些相关的答案,但没有实现我的目标。

  1. Do Java arrays have a maximum size?
  2. How many data a list can hold at the maximum
  3. Why I can't create an array with large size?

有些人给出了一些逻辑,根据文档 “一些虚拟机在数组中保留了一些标题词”。所以对于header words,减去8。但那样的话,如果标题词需要超过 8 个,那么答案会是什么?

请在此基础上澄清我。预先感谢您的合作。

最佳答案

阅读上面关于 Java Memory management 的文章,其中明确指出

我认为这适用于 ArrayList,因为它是可调整大小的数组实现。

Java 数组对象剖析

The shape and structure of an array object, such as an array of int values, is similar to that of a standard Java object. The primary difference is that the array object has an additional piece of metadata that denotes the array's size. An array object's metadata, then, consists of: Class : A pointer to the class information, which describes the object type. In the case of an array of int fields, this is a pointer to the int[] class.

Flags : A collection of flags that describe the state of the object, including the hash code for the object if it has one, and the shape of the object (that is, whether or not the object is an array).

Lock : The synchronization information for the object — that is, whether the object is currently synchronized.

Size : The size of the array.

最大尺寸

2^31 = 2,147,483,648 

作为数组,它本身需要 8 个字节 来存储大小2,147,483,648

所以

2^31 -8 (for storing size ), 

因此最大数组大小定义为 Integer.MAX_VALUE - 8

关于java - 为什么 ArrayList 的最大数组大小是 Integer.MAX_VALUE - 8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35756277/

24 4 0