Skip to content
Advertisement

Custom Edge with jgrapht

I want to define a custom edge

public class Connection extends DefaultWeightedEdge

But when I try to use the super()is that possible? What should I use for EdgeFactory when creating a graph?

new SimpleWeightedGraph<Sensor, Connection>(EdgeFactory.class);

Would this be sufficient? Or should I create a new class who extends EdgeFactory as well?

Advertisement

Answer

You do not require to subclass DefaultWeightedEdge to create your custom edge, the following works also. I’m currently using version 0.9.0 of JGraphT.

Class definition :

public class Connection {
    // class implementation
    // define all constructors and methods you need
}

Graph creation :

SimpleWeightedGraph<Sensor, Connection> graph;
graph = new SimpleWeightedGraph<Sensor, Connection>(Connection.class);

Adding custom edge and setting weight :

Sensor v1 = // sensor instance
Sensor v2 = // another sensor instance
graph.addVertex(v1);
graph.addVertex(v2);

Connection connection = new Connection(/* ... */);
graph.addEdge(v1, v2, connection);
graph.setEdgeWeight(connection, 10.0);

Also consider to implement equals and hashCode methods of your Connection class, as JGraphT relies on those methods since version 0.8.4, see EqualsAndHashCode article. This article also provides an example where DefaultWeightedEdge is subclassed.

Advertisement