Most of them only mentioned that the object header would occupy space, but their answers didn’t answer my question, such as why the size of the object header affects the size of the array. The object header and the contents of the array are not stored in the same array. I mean that the object header and the array should not affect each other in terms of space occupation. Even if their combined size exceeds Interger.MAX_VALUE, their contents are not stored in the same array.
- Why the maximum array size of ArrayList is Integer.MAX_VALUE – 8?
- Why I can’t create an array with large size?
1
Your assertion of “object header and the contents of the array are not stored in the same array” is not correct. Looking at the linked article of the answer of your first linked question (archive link), an Array
object stores all of its data in a single contiguous region of memory, starting with the object header and the length.
See the image from the article:
Note: If the array had more than a single int element, it would just get appended on.
How the memory is laid out within the JVM has not much to do with how you access it from code. If you, for example, access arrObj[2]
the JVM will “calculcate” the offset for you to get the right element.
This answer also provides some reasoning why a Java Object generally shouldn’t exceed a size of Integer.MAX_VALUE