好吧,我有一些类(顶点),其中包含 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())工作正常,我已经测试了数百次;