AMine Bendriss
AMine Bendriss

Reputation: 1

How can I create multiple edges with the same weight and same source vertex?

I'm using jgrapht and I'm having a problem here. As soon as I create two edges with the same weight from one source vertex, I end up having just one edge:

DirectedWeightedPseudograph<Object, Object> Grph1 = new DirectedWeightedPseudograph<>(Object.class);

    Grph1.addVertex("a");
    Grph1.addVertex("b");
    Grph1.addVertex("c");

    Grph1.addEdge("a", "b", "55");
    Grph1.addEdge("a", "c", "55");

I expect the output:

a--55-->b
a--55-->c

But the actual output:

a--55-->b
c

Upvotes: 0

Views: 551

Answers (2)

Marco13
Marco13

Reputation: 54649

You are not creating two edges. You are only creating one edge, and this edge is "55". Right: The string "55" is the edge in your example.

In order to create multiple edges with real weights (pun intended), you should declare your graph to have the right type, namely one that uses, for example, DefaultWeightedEdge as the edge type.

Then, when you add a new edge by calling addEdge, you receive the DefaultWeightedEdge instance. Using this instance, you can assign the weight to this edge, by calling setEdgeWeight.

Graph<String, DefaultWeightedEdge> g = new DirectedWeightedPseudograph<>(DefaultWeightedEdge.class);
g.addVertex("a");
g.addVertex("b");
g.addVertex("c");

DefaultWeightedEdge e0 = g.addEdge("a", "b");
g.setEdgeWeight(e0, 55.0);

DefaultWeightedEdge e1 = g.addEdge("a", "c");
g.setEdgeWeight(e1, 55.0);

System.out.println(g.edgeSet());

Upvotes: 1

Joris Kinable
Joris Kinable

Reputation: 2411

From the documentation:

adds the specified edge e to this graph if this graph contains no edge e2 such that e2.equals(e)

Object o1=Grph1.addEdge("a", "b", "55");
Object o2=Grph1.addEdge("a", "c", "55");
boolean test=o1.equals(o2); //this will return true

Instead of creating your graph with <Object,Object>, use something different, e.g. <String,DefaultWeightedEdge> as is done in the examples:

Graph<String,DefaultWeightedEdge> g=new DirectedWeightedPseudograph<>(DefaultWeightedEdge.class);
g.addVertex("a");
g.addVertex("b");
g.addVertex("c");

g.addEdge("a", "b", "55");
g.addEdge("a", "c", "55");

Upvotes: 0

Related Questions