The problem is that you need to copy the node IDs, not just their values. In particular, when you copy some nodes, you need to deal with the identifiers of the nodes it refers to; this means that the copy constructor or some other mechanism of purely local copy cannot do this work, since it only deals with one node at a time. I'm not sure if this makes sense, but I typed it and my backspace key is not working.
In any case, what you can do is pass another object that can determine which new node corresponds to the old node. If you want to be a fantasy (and who not?), You can call it a graph isomorphism . It can be something as simple as a map. As in this completely untested code:
// in Graph public Graph deepCopy () { Graph g = new Graph(); g.nodes = new ArrayList<Node>(); Map<Node, Node> isomorphism = new IdentityHashMap<Node, Node>(); for (Node n : nodes) { g.nodes.add(n.deepCopy(isomorphism)); } return g; } // in Node public Node deepCopy(Map<Node, Node> isomorphism) { Node copy = isomorphism.get(this); if (copy == null) { copy = new Node(); isomorphism.put(this, copy); for (Node connection: connections) { copy.connections.add(connection.deepCopy(isomorphism)); } } return copy; }
Sergius mentions the use of serialization; serialization actually does something quite similar when it crosses an object graph.
Tom anderson
source share