Menu

containsVertex

Adam
2012-04-19
2013-05-29
  • Adam

    Adam - 2012-04-19

    Hi All,
    There is an explanation in containsVertex API doc:
    [quote]Returns:
    true iff this graph contains a vertex vertex
    How does the method work If the vertex object is some composite object? E.g. for the vertex class shown below

    public class VertexClass {
    
        HashMap<Integer,Thread> field1;
        ArrayList<String,Thread> field2;
        DirectedSparseGraph<String, String>;
        .....
    
    }
    

    how the containsVertex will act? Does it look for a node having the same reference as a given vertex v, or  having the same (as v) values of particular fields?

    In other words (and for the simpler example):
    for the vertex type

    public class VertexClass {
        String field1;
        String field2;
    }
    

    and the graph

        DirectedSparseGraph<VertexClass, String> [b]g[/b];
    

    will the operation

    g.addEdge("Some edge", new VertexClass("a","b"),new VertexClass("a","b"))
    

    add two or one vertex?

     
  • Joshua O'Madadhain

    Think of it as being analogous to Set.contains() or Map.containsKey().

    More precisely, it will depend on your implementation of the equals() and hashCode() methods on your object.

    (Side point: there's nothing to stop you from including a Graph object in your VertexClass, but we don't recommend it as a general practice; it at least complicates matters if you're trying to share vertices between graphs.  We went down that road in JUNG 1.x, and moving away from that was one of the major motivations for the API change that came with JUNG 2.0.)

    To answer your specific question for the simple example as you wrote it: it will add two vertices.  You overrode neither hashCode() nor equals(), so those two objects will have different hash codes and will not return true for x.equals(y).

    You very often-I am tempted to say, "almost always"-will want to override both equals() and hashCode() when building composite objects like that.  Guava's Objects.hashCode() method may be useful to you here:
    http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Objects.html#hashCode(java.lang.Object…)
    (once you figure out which fields should be involved).

    Joshua

     
  • Adam

    Adam - 2012-04-19

    Thanks for the comprehensive explanation,
    Adam

     

Log in to post a comment.