3

我需要制作一个简单图表的副本。

我在图生成器中看不到图复制器,并且 UndirectedGraph 没有实现克隆方法。

年,我可以用手抄一张图。但我想在一行中做到这一点。

4

2 回答 2

2

UndirectedGraph 是一个接口。然而,大多数具体的子类(例如 SimpleGraph)都扩展了 AbstractBaseGraph,后者实现了 clone() 方法。

所以,如果你能保证你手中的UndirectedGraph继承自AbstractBaseGraph,只需转换为AbstractBaseGraph并调用clone方法。

public void someMethod(UndirectedGraph g)
{
  // Do some stuff...

  ((AbstractBaseGraph)g).clone(); // <== Your 1-liner

  // Do some more stuff...
}

但请记住,根据 JavaDoc,clone() 方法执行的是浅克隆。因此,图形实例被克隆,但其中的顶点和边不是。

于 2013-04-04T19:59:33.310 回答
0

A very crude (but quick) solution to copy a graph would be:

    DirectedGraph<String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
    DirectedGraph<String, DefaultEdge> revGraph = new EdgeReversedGraph<>(graph);
    DirectedGraph<String, DefaultEdge> graphCopy = new EdgeReversedGraph<>(revGraph);
    //To reduce the memory complexity
    revGraph = null;

However, it is to be kept in mind that the solution would have high memory & computation complexity if the graph is too big. Discarding the intermediate reversed graph would improve the solution.

于 2016-01-02T19:32:43.560 回答