Reputation: 1
In Java I am creating a tree to function like a basic file system. When I try to add a child to the root node, I get a "stackoverflowerror". I read online that the error means there is too much recursion somewhere but I can't see where that is. How do I fix my code to keep from getting the error? Thank You!
public class Node<File> {
private File data = null;
private Node<File> parent = null;
private List<Node<File>> children = new ArrayList<>();
public Node(File data){
this.data = data;
}
public Node(File data, Node<File> parent){
this.data = data;
this.setParent(parent);
}
public List<Node<File>> getChildren(){
return children;
}
public void addChild(File data){
Node<File> child = new Node<>(data);
child.setParent(this);
this.children.add(child);
}
public void addChild(Node<File> child){
child.setParent(this);
this.children.add(child);
}
public void addChildren(List<Node<File>> children){
children.forEach(each -> each.setParent(this));
this.children.addAll(children);
}
public void setParent(Node<File> parent) {
parent.addChild(this);
this.parent = parent;
}
public File getData(){
return this.data;
}
public void setData(File data){
this.data = data;
}
public boolean isRoot(){
return (this.parent == null);
}
public boolean isLeaf(){
return this.children.isEmpty();
}
public Node<File> getParent(){
return parent;
}
public Node<File> getRoot(){
if(parent == null){return this;}
return parent.getRoot();
}
public void remove(){
if(parent!=null){
parent.removeChild(this);
}
}
private void removeChild(Node<File> child) {
if(children.contains(child)){
children.remove(child);
}
}
}
Upvotes: 0
Views: 237
Reputation: 504
I think that your addChild() and setParent() methods delegate to each other, causing an infinite loop, and that's why the stack is overloaded with infinite recursion.
You should have some stop condition to avoid this loop.
addChild() calls child.setParent() on child, and setParent() calls addChild() on the parent once again, and the story goes on without any way to finish.
Yet, you should also examine the stack-trace to confirm that this is the case.
Upvotes: 2