嗯,我有一些类(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
是错误的概念。您在“from”图中有一组节点,并且您正在“to”图中创建一组新节点。 created.add(copyTo)
将从“to”图中添加一个新节点到集合中。但是当你通过 created.iterator
要查看节点是否已存在,您需要从 copyFromNeighs
查找节点,它是“from”图中的一个节点。在我看来,这永远不会成功。否则,结果将是“to”图中的节点指向“from”图中的节点。
基本上,我相信你需要 created
成为HashMap<Vertex,Vertex>
,不是一个集合。 HashMap
的“ key ”将是“from”图中的一个节点,“value”将是“to”图中的相应节点。然后,当您查看“from”节点的邻居时,您会从映射中获取相应的“to”节点(如果它已被复制),并将其添加到新创建的“to”节点的邻居中。
关于Java图(结构)深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18990950/