那麼,我有一些類(頂點),其中包含HashSet;並且在某些時候,我需要深入複製該元素;Java圖形(結構)深度複製
我寫了一些代碼,但有時它不起作用;我正在研究這個bug幾天,無法修復它......如果有人有足夠的時間閱讀代碼並找到它,我會非常感激。先謝謝你。
嗯,這裏是功能:
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())工作正常,我測試過他們幾百時間;
我忘了說,那Vertex.id始終是唯一的,所以我像overrided頂點的哈希函數: –
@覆蓋 公衆詮釋的hashCode(){ \t \t回報this.id; \t} –
你想複製單個頂點還是整個圖?而且,你的意思是「不起作用」? –