1. 程式人生 > >為什麼ArrayList的最大陣列大小是Integer.MAX_VALUE

為什麼ArrayList的最大陣列大小是Integer.MAX_VALUE

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

程式碼之美就在於此,只能感嘆聲,寫底層的作者真聰明。