javajgraphtjgraph

How to have characterize edges in DefaultDirectedGraph or JGraphT?


I am using DefaultDirectedGraph to create my directed graph, where each vertex is an object.

DefaultDirectedGraph g = new DefaultDirectedGraph(DefaultEdge.class);

I was wondering if it is possible to characterize the edges? For example, I would like to keep the information of the friendship between students.

Or should I have a map between edges and the objects of friendship?


Solution

  • You can certainly store information on the edges. Here is a usecase I recently used myself:

    public class Intersection{
        public final long latitude;
        public final long longitude;
        public Intersection(long latitude, long longitude){ ...}
    }
    
    public class Street extends DefaultWeightedEdge{
        public final String streetName;
        public final int speedLimit;
        public final Street(...){...}
    }
    
    public class RoadNetwork{
        public final Graph<Intersection, Street> network=new DefaultDirectedGraph<>(Street.class);
        Intersection i1=new Intersection(..);
        Intersection i2=new Intersection(..);
        Street s=new Street(..);
    
        //Network with 1 street
        network.addVertex(i1);
        network.addVertex(i2);
        network.addEdge(i1,i2,s);
    }
    

    Notes:

    1. Street extends DefaultWeightedEdge: it is no longer necessary to extend DefaultEdge or DefaultWeightedEdge in recent versions of jgrapht
    2. In jgrapht, all edges are objects. When you use custom objects (such as Street) in the above example, you can only use the addEdge(vertex1, vertex2, edgeObject) method. You cannot use the addEdge(vertex1,vertex2) method unless you provide an EdgeFactory to the graph constructor.
    3. A common mistake is to store graph information on the edges. E.g. it would be wrong to store the source and target Intersection (the 2 endpoints of the street) on the street object itself. This information is stored in the graph.
    4. When implementing your own vertex or edge classes, you must implement the equals and hashCode methods.See https://github.com/jgrapht/jgrapht/wiki/Users:-EqualsAndHashCode for details.