I have a class Node
which has a variable of Generic type.
class Node{
Object obj;
}
If I am creating an array of Node objects, How much memory will be allocated for that array?
Node[] arr = new Node[10];
I have a class Node
which has a variable of Generic type.
class Node{
Object obj;
}
If I am creating an array of Node objects, How much memory will be allocated for that array?
Node[] arr = new Node[10];
Firstly, the correct way to implement generic types in Java is to use generics and not simply use the Object
class.
However, to answer your question it would allocate 4 bytes
per object, so for your array of size 10
that would 40 bytes
.
Java doesn't store the object in the array itself, instead, it would store a reference to the object. The objects themselves would get their own block of memory allocated at the time the object was constructed.
To fully understand references I recommend the answer to this question
First, there are no "Generics" involved here. Second, the types Node
, Object
, Node[]
, etc. in Java are what are known as "reference types". The value of a variable of type Node
or Object
is not an "object", but rather a "reference", basically, a pointer to an object. The value of type Node[]
is a reference to an array object which holds references. In new Node[10]
, you are creating an array object which holds 10 references (basically, 10 pointers). All the pointers start out as null
. So the space this takes up is the space taken up by 10 pointers, plus the space for the object metadata of the array object. The space each reference (pointer) takes up can vary by Java virtual machine implementation, but is usually 4 bytes on 32-bit and 8 bytes on 64-bit. What fields the Node
class might contain is irrelevant; the array does not store Node
objects.
I did 1 minute googling... https://study.com/academy/lesson/java-arrays-memory-use-performance.html
So the size of the array is 12 + 10*4 + 4 = 56 bytes.