Protected? getSource and getTarget methods on JGraphT DefaultEdge class
Asked Answered
C

2

17

The methods getSource() and getTarget() of DefaultEdge on org.jgrapht.graph.DefaultEdge are protected.

How should I access source and target vertices of each of the edges returned by the edgeSet() of org.jgrapht.graph.SimpleGraph ?

The code below shows what is happening.

import java.util.Set;

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

public class TestEdges
{
    public static void main(String [] args)
    {
        UndirectedGraph<String, DefaultEdge> g =
            new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);

        String A = "A";
        String B = "B";
        String C = "C";

        // add the vertices
        g.addVertex(A);
        g.addVertex(B);
        g.addVertex(C);

        g.addEdge(A, B);
        g.addEdge(B, C);
        g.addEdge(A, C);

        Set<DefaultEdge> edges = g.edgeSet();

        for(DefaultEdge edge : edges) {
            String v1   = edge.getSource(); // Error getSource() is protected method
            String v2   = edge.getTarget(); // Error getTarget() is protected method
        }
    }
}
Charade answered 12/1, 2013 at 18:18 Comment(0)
C
34

The "correct" method to access edges source and target, according to JGraphT mailing list is to use the method getEdgeSource(E) and getEdgeTarget(E) from the interface Interface Graph<V,E> of org.jgrapht

the modification of the code is then

for(DefaultEdge edge : edges) {
   String v1   = g.getEdgeSource(edge);
   String v2   = g.getEdgeTarget(edge);
}
Charade answered 13/1, 2013 at 14:36 Comment(0)
R
1

I was having a similar issue when trying to extract the values of the edges, and although not OP's case, might be helpful for anyone else facing this issue.

When I instantiated my graph and passed it an edge class:

DirectedGraph graph = new SimpleDirectedGraph(DefaultEdge.class);

Netbeans gave me the option for what DefaultEdge.class file to import, I chose the wrong one. I used the org.jgraph library instead of the org.jgrapht.

If you are using the DefaultEdge class make sure you are using the one from jgrapht.

import org.jgrapht.graph.DefaultEdge;
Rothmuller answered 6/11, 2014 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.