I have a Node object and want to make some clone objects from this orginal one. Below is my code:
public class Main {
    public static void main(String[] args) {
        Node node = new Node();
        node.setName("node1");
        node.setValue("1");
        node.setChildNodes(new ArrayList<>());
        Node node2 = cloneNode(node);
        Node childNode2 = new Node();
        childNode2.setName("childNode2");
        childNode2.setValue("1");
        List<Node> childNodes2 = node2.getChildNodes();
        childNodes2.add(childNode2);
        node2.setChildNodes(childNodes2);
        System.out.println(node.getChildNodes());
    }
    private static Node cloneNode(Node node) {
        Node newNode = new Node();
        newNode.setName(node.getName());
        newNode.setValue(node.getValue());
        newNode.setChildNodes(node.getChildNodes());
        return newNode;
    }
}
class Node {
    private String name;
    private String value;
    private List<Node> childNodes;
    //getter and setter
}
I created a first Node and create a second Node which is cloned from the first one. Then I would like to modify the childNodes list in the second Node object (node2) and then I realize that the childNodes list in the first Node(node) is also modified.
How can I avoid the list in the first Node being modified?
Thank you so much!
 
     
    