Eh bien, j'ai une classe (Vertex), qui contient HashSet; et à un moment donné, j'ai besoin de copier profondément cet élément; J'ai écrit du code, mais parfois cela ne fonctionne pas; Je travaille sur ce bug depuis plusieurs jours et je ne peux pas le réparer ... Si quelqu'un a assez de temps pour lire le code et le trouver, je serai très reconnaissant. Merci d'avance.Java Graphique (Structure) Copie en profondeur
Eh bien, voici la fonction:
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;
}
et je veux cette méthode pour copier de CopyFrom à CopyTo. Voici comment j'appelle cette méthode:
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);
autres méthodes (comme .getNEighbours(), .addNeighbours()) fonctionnent correctement, je les ai testé des centaines de fois;
J'oubliais de dire que Vertex.id est toujours unique, donc j'ai overrided fonction de hachage de Vertex comme ça: –
@Override hashCode public int() { \t \t retour this.id; \t} –
voulez-vous copier un seul sommet ou le graphe entier? Et, que voulez-vous dire par "ne fonctionne pas"? –