5

in JUNG 1.7.6 there was the function copy() for this purpose (myGraph.copy()), but in JUNG 2.0 this function does not exist anymore. I could not find any other possibility to create a copy of a graph object. I would be very glad if someone could help me. A workaround would be nice, too.

Thanks a lot!

user1377963
  • 115
  • 1
  • 9

3 Answers3

7

Code below with generics, so you should replace V and E with String for your Graph<String, String>.

    Graph<V, E> src;
    Graph<V, E> dest;

    for (V v : src.getVertices())
        dest.addVertex(v);

    for (E e : src.getEdges())
        dest.addEdge(e, src.getIncidentVertices(e));
Vadim Ponomarev
  • 1,346
  • 9
  • 15
  • This is basically correct, but one nitpick and one enhancement: (1) you should not replace V,E with String, but with the types of your graph (and if you create your own static method you won't even need or want to do that). (2) If you know a priori that all of your vertices have incident edges, and you're using the Graph classes that JUNG provides, you can leave out the first loop; addEdge will add the incident edges if they are not present. – Joshua O'Madadhain May 06 '12 at 21:52
0

You can copy the graph manually by iterating over all vertices and all edges and adding them to a new graph. See getVertices() in the API

mbatchkarov
  • 15,487
  • 9
  • 60
  • 79
  • If I have a Graph the function getVertices() returns a Collection with the vertices. The function getEdges() returns a Collection with the edge ids, but I don't get the vertices which are connected by this edge... the only way I found to see which vertices are connected by a specific edge is to print the graph.toString() method... – user1377963 May 06 '12 at 12:40
0

You could do a simple copy of vertices & edges, that would create a new Graph, but the objects inside will be passed by reference so you could use this cloning library https://code.google.com/p/cloning/

and do a deep copy:

Cloner cloner = new Cloner();
Graph<V, E> clonedGraph = cloner.deepClone(graph);
Elyran
  • 313
  • 2
  • 10