[英]Java Graph (Structure) Deep copy
好吧,我有一些类(Vertex),其中包含HashSet。 在某个时候,我需要深深复制该元素;
我写了一些代码,但有时不起作用。 我正在为这个错误工作几天,而且无法修复...如果有人有足够的时间阅读代码并找到它,我将非常感激。 先感谢您。
好吧,这是函数:
public Vertex getCopy(Vertex copyFrom, Vertex copyTo, HashSet<Vertex> created){
copyTo.setId(copyFrom.getId());
copyTo.setColor(copyFrom.getColor());
copyTo.setCount(copyFrom.getCount());
copyTo.setDepth(copyFrom.getDepth());
copyTo.setDistance(copyFrom.getDistance());
copyTo.setHeurist(copyFrom.getHeurist());
copyTo.setVisited(copyFrom.isVisited());
copyTo.setPath(copyFrom.getPath());
created.add(copyTo);
HashSet<Vertex> copyToNeighs = new HashSet<Vertex>();
HashSet<Vertex> copyFromNeighs = new HashSet<Vertex>();
copyFromNeighs.addAll(copyFrom.getNeighbours());
Iterator<Vertex> it = copyFromNeighs.iterator();
while (it.hasNext()){
Vertex curr = it.next();
if (!created.contains(curr)){
Vertex newOne = new Vertex();
newOne = getCopy(curr, newOne, created);
copyToNeighs.add(newOne);
} else {
Iterator<Vertex> itr = created.iterator();
while (itr.hasNext()){
Vertex tmp = itr.next();
if (tmp.equals(curr)){
copyToNeighs.add(tmp);
break;
}
}
}
}
copyTo.setNeighbours(copyToNeighs);
return copyTo;
}
我想这种方法从CopyFrom复制到CopyTo。 这是我如何调用此方法:
Vertex newOne = new Vertex();
Vertex newCurr = new Vertex();
HashSet<Vertex> seen1 = new HashSet<Vertex>();
HashSet<Vertex> seen2 = new HashSet<Vertex>();
newOne = newOne.getCopy(tmp, newOne, seen1);
newCurr = newCurr.getCopy(curr, newCurr, seen2);
其他方法(例如.getNEighbours()、. addNeighbours())可以正常工作,我已经对其进行了数百次测试;
created
是错误的概念。 您在“从”图中有一组节点,并且在“到”图中创建了一组新节点。 created.add(copyTo)
会将“ to”图中的新节点添加到集合中。 但是,当您遍历created.iterator
来查看是否已存在某个节点时,您正在从copyFromNeighs
寻找一个节点,后者是“ from”图中的一个节点。 在我看来,这将永远不会成功。 否则结果将是您将在“到”图中有指向“从”图中的节点的节点。
基本上,我相信您需要created
为HashMap<Vertex,Vertex>
,而不是集合。 HashMap
的“键”将是“从”图中的一个节点,而“值”将是“到”图中的相应节点。 然后,当您查看“ from”节点的邻居时,您将从地图中获得相应的“ to”节点(如果已经复制),并将其添加到新创建的“ to”节点的邻居中。
创建深层副本的最简单方法是序列化到内存中,然后反序列化,请参见以下问题: 如何在Java中制作对象的深层副本?
您需要更一致的方式将源顶点映射到结果顶点。 声明created
为哈希图,而不是哈希集。 仅在created.get(oldVertex)==null
时创建新顶点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.