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

资料链接stackoverflow

Read the above article about Java Memory management, which clearly states

I think this applies to ArrayList as it is the Resizable array implemenation.

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.

max size

2^31 = 2,147,483,648 

as the Array it self needs 8 bytes to stores the size 2,147,483,648

so

2^31 -8 (for storing size ), 

so maximum array size is defined as Integer.MAX_VALUE - 8

翻译一下:

数组对象的形状和结构(如int值数组)与标准Java对象类似。主要区别在于数组对象有一个额外的元数据,用于表示数组的大小。然后,数组对象的元数据由以下部分组成:Class:指向描述对象类型的类信息的指针。在int数组的情况下,这是一个指向int []类的指针。

标志:描述对象状态的标志集合,包括该对象的散列码(如果有)以及对象的形状(即对象是否为数组)。

锁定:对象的同步信息 - 即对象是否当前同步。

大小:数组的大小。

最大尺寸

2^31 = 2,147,483,648 

作为自己需要8 bytes存储大小 的数组2,147,483,648

所以

2^31 -8 (for storing size ), 

所以最大数组大小定义为Integer.MAX_VALUE - 8

代码之美就在于此,只能感叹声,写底层的作者真聪明。

猜你喜欢

转载自blog.csdn.net/chineseyoung/article/details/80787071
今日推荐