I am studying Java 8 documentation for ArrayList
. I got that maximum array size is defined as Integer.MAX_VALUE - 8
means 2^31 – 8 = 2 147 483 639. Then I have focused on why 8 is subtracted or why not less than 8
or more than 8
is subtracted?
/**
* 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;
I got some related answers but not fulfilling my thrust.
Some people given some logic that as per documentation "Some VMs reserve some header words in an array"
. So for header words, 8 is subtracted. But on that case, if header words need more than 8, then what will be the answer?
Please clarify me on that basis. Advance thanks for your cooperation.
The theoretical limit for ArrayList capacity is Integer. MAX_VALUE, a.k.a. 2^31 - 1, a.k.a. 2,147,483,647.
Integer. MAX_VALUE represents the maximum positive integer value that can be represented in 32 bits (i.e., 2147483647 ). This means that no number of type Integer that is greater than 2147483647 can exist in Java.
The 32-bit Java int can go to a maximum of 2,147,483,647, so that is the theoretical maximum Java array size.
Java uses an integer as an index to the array and the maximum integer store by JVM is 2^32. so you can store 2,147,483,647 elements in the array. In case you need more than max-length you can use two different arrays but the recommended method is store data into a file. because storing data in the file has no limit.
Read the above article about Java Memory management, which clearly states
I think this applies to ArrayList as it is the Resizable array implemenation.
Anatomy of a Java array object
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With