Reputation: 121998
Consider the below case
int[] anArray = new int[10];
Allocates memory for 10 elements of each 32-bit on heap.Right ?
So what is the size of the element if the element type is Object. ??
like
Object[] objArray = new Object[10];
How much memory allocated now on heap ? I just got the doubt by ssing the source code of ArrayList
.
private transient Object[] elementData;
Just tried this line in my machine
List<String> s = new ArrayList<String>(Integer.MAX_VALUE);
results
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at java.util.ArrayList.<init>(Unknown Source)
at com.nextenders.server.guice.actions.servlets.Test.main(Test.java:13)
So I'm trying to know how much memory allocated.
Upvotes: 4
Views: 192
Reputation: 718678
So what is the size of the element if the element type is Object. ??
The size of an Object[]
array element is the size of a reference.
On a 32 bit JVM, a reference is 32 bits (4 bytes)
On a 64 bit JVM, a reference is 64 bits (8 bytes), or 32 bits if the "compressed oop" optimization is enabled and the heap size is less than 32Gb.
So your array allocation will allocate a heap object containing roughly 4 x 10 or 8 x 10 bytes ... plus about 12 bytes of object header overhead.
Just tried this line in my machine
List<String> s = new ArrayList<String>(Integer.MAX_VALUE);
Under the covers, you are attempting to allocate attempting to allocate an array containing between 233 and 234 bytes. With a 32bit JVM, that is guaranteed to not work. With a 64 bit JVM, you'd need a heap of at least 8Gb (compressed oop) or 16Gb for that to work.
Upvotes: 4
Reputation: 1605
It will create an array of 10 32 bit references to objects (the memory address where the object is stored) as all objects in java are just pointers to the memory where the object is stored. Or if you are using a 64 bit machine the addresses will be 64 bits
Upvotes: 0
Reputation: 361
Upvotes: 0