Java图(结构)深拷贝

标签 java 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是错误的概念。您在“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/

相关文章:

java - JPA CriteriaQuery OneToMany

c++ - 聚合结构构造函数

java - 深度复制“对象”类型

java - IntByReference 返回 0 而不是实际值

Java Hashmap 迭代 : Look at two values at once?

java - 单击 JButton 时如何更新它的外观?

javascript - 从 json 对象创建定义列表

C结构: member order and memory allocation

python - Numba - jitclass 实例的副本

java - 这会是深拷贝的一个例子吗?