【问题标题】:deep copy for a graph using hashmap does not work使用 hashmap 的图的深层复制不起作用
【发布时间】:2013-05-17 10:31:34
【问题描述】:

我有一个有向图,其边为Map<E,Pair<V>>,顶点为<V>。

我想要此图表的副本,并在原始图表不变的情况下在副本中进行一些更改。

我编写了两个不同的复制函数,copy1 和 copy2。第二个函数工作正常,但是,在 copy1 中,如果我从复制图中删除一个顶点,它也会从原始图中删除。你能告诉我 copy1 有什么问题吗?如何快速复制我的图表?

public Graph<V> copy1() {
        Graph<V> g = new Graph<V>();
        g.vertices.putAll(super.vertices);
        g.edges.putAll(super.edges);
        return g;
    }

public static  void copy2(IGraph<E> graph, IGraph<E> copy) {
        assert (copy.getVertexCount() == 0);

        for (E resource : graph.getVertices()) {
            copy.addVertex(resource);
        }
        for (Edge edge : graph.getEdges()) {
            Pair<E> endpoints = graph.getEndpoints(edge);
            copy.addEdge(edge, endpoints);
        }
    }

【问题讨论】:

  • 如果我们看不到 addVertex 和 addEdge 的功能就很难做到
  • 问题 - 为什么一个顶点映射到一对映射?我可以理解 vertices = Map> (虽然有一个 Map> 会更简单),但是为什么要多出一对呢?
  • 我在jung.sourceforge.net/doc/api/edu/uci/ics/jung/graph/…中使用了类DirectedSparseGraph

标签: java hashmap deep-copy


【解决方案1】:

使用 this 作为方法,使其与递归新创建的所有对象完美的 deepCopy

public static <T extends Serializable> T deepCopy(T o) throws Exception
{
    if (o == null)
        return null;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);

    oos.writeObject(o);
    bos.close();
    oos.close();

    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bis);

    T t = (T) ois.readObject();
    bis.close();
    ois.close();
    return t;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多