Simple undirected unlabelled graph in JGraphT doesn't work? What is the edgeClass parameter?

StackOverflow https://stackoverflow.com/questions/16218204

質問

I want to make a simple undirected unlabelled (edges aren't labelled) graph A<->B in JGraphT 0.8.3:

import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;

class A {
    public static void main(String[] args) {
        SimpleGraph<String, String> sg =
            new SimpleGraph<String, String>(String.class);
        sg.addVertex("A");
        sg.addVertex("B");
        sg.addEdge("A", "B");
        System.out.println("edges of A: " + sg.edgesOf("A"));
        System.out.println("edges of B: " + sg.edgesOf("B"));
    }
}

I get this output:

$ java -cp 'jgrapht-jdk1.6.jar:.' A
edges of A: []
edges of B: []

Why are the sets of edges of vertices A and B empty? Also what is the class parameter of SimpleGraph for? It seems to be the type of edges, but since my edges here are unlabelled, surely it doesn't matter? All the graph classes seem to take the class of the edge (edgeClass) as a parameter. I can't find where in the documentation edgeClass is described.


I found if I label the edge (change the addEdge line to sg.addEdge("A", "B", "an_edge");) then it works... but I don't want to label the edges...

$ java -cp 'jgrapht-jdk1.6.jar:.' A
edges of A: [an_edge]
edges of B: [an_edge]
役に立ちましたか?

解決

You don't have to label the edges. the problem in your approach is that you tell the graph to use String as edge type. A proper std. way of doing things would be:

    SimpleGraph<String, DefaultEdge> sg = new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);
    sg.addVertex("A");
    sg.addVertex("B");
    sg.addVertex("C");
    sg.addEdge("A", "B");
    sg.addEdge("B", "C");
    System.out.println("graph: " + sg.toString());
    System.out.println("edges of A: " + sg.edgesOf("A"));
    System.out.println("edges of B: " + sg.edgesOf("B"));

this will give you the following output:

graph: ([A, B, C], [{A,B}, {B,C}])
edges of A: [(A : B)]
edges of B: [(A : B), (B : C)]

So to fix the problem it is necessary to switch your edge class to DefaultEdge as shown in the code.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top