I have the class:
public class Node
{
private String id;
private List<Node> children;
}
I need to create a deep copy of a List of it List, but given that there might circular references I was trying implementing the Cloneable
interface and overriding the clone
method but I keep getting Stackoverflow exception, so I wonder if there is a way to deep copy it that's fast and removes the circular dependencies in the process?
Class using cloneable, when I try to clone and it has circular references I get the error mention about
public class Node implements Cloneable
{
private String id;
private List<Node> children;
@Override
public Object clone() throws CloneNotSupportedException {
Node clone = (Node) super.clone();
if (children != null) {
List<Node> cloneChildren = new ArrayList<>(children.size());
for (Node child : children) {
cloneChildren.add((Node) child.clone());
}
clone.setChildren(cloneChildren);
}
return clone;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
}