I'm trying to get two nodes to link together. When n
adds s
as a link, s
should also update to add n
as a link. But the code calls itself and gets stuck in an infinite loop, then overflows. How can I get the nodes to assign to each other, but not recursively assign themselves?
public class Node {
Set<Node> connections = new HashSet<Node>();
public static void main(String args[]) {
Node n = new Node();
Node s = new Node();
n.addNode(s);
}
public Node() {
}
public void addNode(Node newNode) {
connections.add(newNode);
newNode.addNode(this);
}
}
Update: I added this code to have the method call another setter
method.
public void addNode(Node newNode) {
connections.add(newNode);
newNode.addSingleNode(this);
}
protected void addSingleNode(Node newNode) {
connections.add(newNode);
}
}