jGraphT DirectedWeightedMultigraph中的等顶点

时间:2014-05-16 17:03:13

标签: java equals directed-graph jgrapht

我想要一个带有“自定义”顶点和边缘的DirectedWeightedMultigraph。 使用此代码,我想只有三个顶点,因为v1和v4具有相同的键,但我有四个。

         DirectedWeightedMultigraph<Vertex, Edge> graph = new DirectedWeightedMultigraph<Vertex, Edge>(Edge.class);

     Vertex v1 = new Vertex("a", "o1");
     Vertex v2 = new Vertex("b", "o2");
     Vertex v3 = new Vertex("c", "o1");
     Vertex v4 = new Vertex("a", "o3");

     graph.addVertex(v1);
     graph.addVertex(v2);
     graph.addVertex(v3);
     graph.addVertex(v4);
     System.out.println("#vertex: "+ graph.vertexSet().size());

这就是我的顶点的样子:

public class Vertex {

String key;
String other;

public Vertex(String id, String o){
    key = id;
    other = o;
}

public boolean equals(Object object) {
    if (object == null || !(object instanceof Vertex)) {
        return false;
    }       
    return (this.key == ((Vertex) object).key);
}   

public boolean isAVertex(Set<Vertex> set) {

    boolean result = false;
     for (Vertex v : set) {
            if (this.equals(v)) { 
                result = true;
                break;
            }
     }
    return result;

}

}

我的边缘看起来像

public class Edge {

int cost;   

}

在使用边缘之前,我阅读了关于equals的thisthis以及关于顶点和边缘的hashCode。我也尝试使用ParanoidGraph,但它不起作用。为了解决这个问题,我选择“手动”检查在添加顶点之前具有特定键的顶点是否在顶点集中。但我想念我的代码中的错误。我还有四个顶点:

         List<Vertex> rowVertices = new ArrayList<Vertex>();
     rowVertices.add(v1);
     rowVertices.add(v2);
     rowVertices.add(v3);
     rowVertices.add(v4);

     Iterator it = rowVertices.iterator();
     while (it.hasNext()) {
         Vertex currentVertex = (Vertex) it.next();

         if (!currentVertex.isAVertex(graph.vertexSet())) {
             graph.addVertex(currentVertex);
         }           
     }

     System.out.println("#vertex: "+ graph.vertexSet().size());

0 个答案:

没有答案