ps0604
ps0604

Reputation: 1071

StackOverflowError building a tree

I'm trying to build a Tree where one node can have multiple children (see below). When I try to run the App below, I get the following in the declaration of the Data case class

Exception in thread "main" java.lang.StackOverflowError

What does this mean?

// data: information stored in the node
// list: list of children nodes
// parent: pointer to the parent
case class Node[A] ( data: A, var list: List[Node[A]], var parent: Node[A] ) 

case class Data (descrip: String)

object Tree extends App {

   val root = Node(Data("root"),null,null)

    val node1 = Node(Data("node1"),null,root)
    val node2 = Node(Data("node2"),null,root)
    val list = List(node1, node2)

    root.list = list 

    println(root)

}

Upvotes: 1

Views: 73

Answers (1)

pedrofurla
pedrofurla

Reputation: 12783

This means your structure has a infinite cycle. root.list contains node1 and node2 and these contain root.

It tries to print (*) root, but to print root it needs to print nodes 1 and 2, but to print these it needs to print root and so on, never ending, eventually blowing up the stack, which is the thing in the JVM that stores method calls information.

(*) The word "print" is used here rather loosely, it is actually the calls to object.toString for each of objects involved.

Upvotes: 2

Related Questions