Techs Techs - 10 days ago 5
Java Question

Maximum call stack size exceeded - Infinite Loop

I have the following JavaScript class:

class TrieNode
{
constructor()
{
switch(arguments.length)
{
case 0 : this.constructorNoParam();
break;
case 1 : this.constructorOneParam(arguments[0]);
break;
}
}

constructorOneParam(c)
{
this.children=new TrieNode();
this.c = c;
this.isLeaf;
}

constructorNoParam()
{
this.children = new TrieNode();
this.c;
this.isLeaf;
}
}


The reason why I am getting this error is that every time I am creating the
children
variable, the constructor creates another instance of the TrieNode class and results in an infinite loop.

Is there a way that I can create only ONE variable for the whole class? I had to put it in the constructor since in JavaScript classes, variables can only be created inside functions.

Basically, what I want to achieve would look like this in java:

public class TrieNode {

public char c;
TrieNode children = new TrieNode();
public boolean isLeaf;

public TrieNode() {}

public TrieNode(char c){
this.c = c;
}


Thanks

Answer

You can create a static variable for this,

class TrieNode {
  constructor(time) {
      if(time === "1") return;
      switch(arguments.length) {
        case 0 : this.constructorNoParam();
        break;
        case 1 : this.constructorOneParam(arguments[0]);
        break;
      }
  }
  constructorOneParam(c) {
      this.children= TrieNode.children;
      this.c = c;
      this.isLeaf;
  }
  constructorNoParam() {
      this.children = TrieNode.children;
      this.c;
      this.isLeaf;
  }
}

TrieNode.children = new TrieNode("1");

// Now the code wont fall into a recursive loop
var x = new TrieNode();
var y = new TrieNode("foo", "bar"); 

And create a provision for the first time setup.

Comments