Reputation: 11
I have a directed graph having edges as Map<E,Pair<V>>
, and vertices as <V>
.
I want to have a copy of this graph and make some changes in the copy while the original graph does not change.
I have written two different copying functions, copy1 and copy2. The second function works fine, however, in copy1, if I remove a vertix from the copy graph, it would be also removed from the original one. Can you tell me what the problem is with copy1 and how can I make a fast copy of my graph?
public Graph<V> copy1() {
Graph<V> g = new Graph<V>();
g.vertices.putAll(super.vertices);
g.edges.putAll(super.edges);
return g;
}
public static void copy2(IGraph<E> graph, IGraph<E> copy) {
assert (copy.getVertexCount() == 0);
for (E resource : graph.getVertices()) {
copy.addVertex(resource);
}
for (Edge edge : graph.getEdges()) {
Pair<E> endpoints = graph.getEndpoints(edge);
copy.addEdge(edge, endpoints);
}
}
Upvotes: 1
Views: 236
Reputation: 396
Use this as a method, so that it is perfect deepCopy with all objects newly created recursively
public static <T extends Serializable> T deepCopy(T o) throws Exception
{
if (o == null)
return null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(o);
bos.close();
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
T t = (T) ois.readObject();
bis.close();
ois.close();
return t;
}
Upvotes: 1