Search code examples
javajung

how to add an edge for two existing nodes/vertexs in jung


can you help me please? how I can add an edge between two nodes/vertexs which those nodes are existed in graph. my graph use custom vertex and custom edge class. here my code

if(findEdge(g,v1,v2)==null) 
g.addEdge(new Edge(), v1, v2, EdgeType.DIRECTED);

where findEdge function is

public Edge findEdge(DirectedGraph<Vertex, Edge> g, Vertex v1,Vertex v2) {
    Collection<Edge> edges = g.getEdges();
    for (Edge ed : edges) { 
        //System.out.print(vt.getLabel() + " ");
        if(ed.getNodeFrom().equals(v1.getLabel())&&ed.getNodeDes().equals(v2.getLabel())) {
            return ed;
        }
    }
    return null;
}

from that function, I can get result about two existed nodes's edge, is existed or null.


Solution

  • First, Graph already has a findEdge() method; look at the API docs that Marco13@ pointed you to.

    Second, as rlegendi@ pointed out, it's not clear whether you want a multigraph or not: if you do, why are you only adding an edge if there isn't one present, and if you don't, why are you creating a DirectedSparseMultigraph object?

    It's not clear what you're trying to accomplish.