0

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];
Faihan
  • 113
  • 1
  • 9

3 Answers3

0

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

Adam Griffiths
  • 680
  • 6
  • 26
  • 60
0

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.

newacct
  • 119,665
  • 29
  • 163
  • 224
-1

I did 1 minute googling... https://study.com/academy/lesson/java-arrays-memory-use-performance.html

  • 12 bytes for the header object
  • 10 elements times 4 bytes (int size)
  • 4 bytes padding

So the size of the array is 12 + 10*4 + 4 = 56 bytes.

Michele Da Ros
  • 856
  • 7
  • 21
  • 1
    I read the link you have attached. This is valid only if the array is for int type values. But the question is for Generic type array. – Faihan Jan 16 '21 at 04:46