0

This is a working java code which is used for implementing trie data structure.

class TrieNode {
TrieNode[] arr;
boolean isEnd;
// Initialize your data structure here.
public TrieNode() {
    this.arr = new TrieNode[26];
}

What I don't understand is how the memory allocation works with

TrieNode[] arr;

code. If it were something like this

class TrieNode {
    int[] arr;
    boolean isEnd;
    // Initialize your data structure here.
    public TrieNode() {
        this.arr = new int[26];
    }

I know that this allocates memory for 26 integers. It's better if you can explain how the memory allocation works for first code. (In compiler's perspective)

EDIT : Sorry if my question is unclear.What im asking is we create array with 26 elements in

new TrieNode[26];

How much memory is allocated?

  • In java all you have references and actual object resides in memory. References refer to the objects in heap. Now when you have `new TrieNode[26]`, you have 26 references of type `TrieNode` (in contigous memory) but actual objects will reside in heap which need not be contigous. – nits.kk Oct 02 '18 at 20:27

2 Answers2

1

Using your first code, When you create object of TriNode like

TriNode t = new TriNode();

JVM will allocate memory to store 26 references for arr elements and 1 reference for isEnd field. To store references , JVM uses 32 bits for a 32 bit JVM and 64 bits for a 64 bit JVM. When you create array

new TrieNode[26];

It will allocate 26*(64bit/32bit)+1 boolean because it doesn't create TrieNode objects instead it creates array of references to store TriNode objects which are not created yet. So when you initialise array elements like

arr[0] = new TrieNode();

Then it will allocate memmory for TrieNode() object and arr[0] will point this object.

So conclusion is JVM will not allocate memory for 26 Trinode objects instead it will allocate memory for their references.

NargiT
  • 61
  • 1
  • 7
0

Up until you do no call new no memory allocation is done.

So TrieNode[] arr; act as a future reference. Only when you call the constructor, Java will allocate the memory and set the reference inside arr.

Links:

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
NargiT
  • 61
  • 1
  • 7
  • How much memory is allocated for TrieNode[] arr; ? because we haven't specified it. Sorry I'm new to programming. – Tharaka Ratnayake Oct 02 '18 at 20:16
  • I don't konw the details but it depends of your JVM. If you run a 32-bits JVM you will get a 32bits per reference if you have a a 64-bits JVM you can get up to 64bits reference. https://stackoverflow.com/questions/1721568/size-of-reference-of-an-class-in-java – NargiT Oct 02 '18 at 20:20
  • No it's not what I'm asking :( I have edited the question – Tharaka Ratnayake Oct 02 '18 at 20:30