title: deep copying a graph structure
body: <p>I have a graph class with Node's, where each Node can connect to others:</p>
  
  <pre><code>public class Node {
    List&lt;Node&gt; connections;
  }
  </code></pre>
  
  <p>I would like to make a deep copy of the entire graph. As a first attempt, I tried making a copy constructor like:</p>
  
  <pre><code>public Node(Node other) {
    connections = new ArrayList&lt;Node&gt;();
    for (Node n : other.connections) { 
      connections.add(new Node(n));
    }
  }
  </code></pre>
  
  <p>So deep copying a graph would just be: </p>
  
  <pre><code>public Graph deepCopy () {
    Graph g = new Graph();
    g.nodes = new ArrayList&lt;Node&gt;();
    for (Node n : nodes) { 
      g.nodes.add(new Node(n));
    }
  }
  </code></pre>
  
  <p>But that doesn't work as that destroys the connection relationship among the nodes. I am wondering if anyone has suggestions to do this in a simple way?  Thanks.</p>