[英]deep copy for a graph using hashmap does not work
I have a directed graph having edges as Map<E,Pair<V>>
, and vertices as <V>
. 我有一个有向图,其边线为
Map<E,Pair<V>>
,顶点为<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. 我编写了两个不同的复制功能,即copy1和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.
第二个函数工作正常,但是,在copy1中,如果我从复制图中删除一个顶点,那么它也将从原始图中删除。 Can you tell me what the problem is with copy1 and how can I make a fast copy of my graph?
您能告诉我copy1的问题是什么,如何快速复制图形?
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);
}
}
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.