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);
}
}
}
setParentlooks suspicious.parent.addChild(this);-- why are you doing that?