JUNG - 自定义边缘和顶点问题

时间:2011-09-14 23:22:19

标签: jung edge vertex

我定义了一个自定义边和顶点类型,用于无向稀疏图。问题是图形添加了多条我不想要的边。例如,考虑以下代码:

UndirectedSparseGraph<Vertex, Edge> graphX = new UndirectedSparseGraph<Vertex, Edge>();
graphX.addEdge(new Edge("1#2"), new Vertex("1"), new Vertex("2"));
graphX.addEdge(new Edge("1#2"), new Vertex("1"), new Vertex("2"));
graphX.addEdge(new Edge("2#1"), new Vertex("2"), new Vertex("1"));
graphX.addEdge(new Edge("1#3"), new Vertex("1"), new Vertex("3"));
graphX.addEdge(new Edge("1#4"), new Vertex("1"), new Vertex("4"));

我故意添加了两个相似的边(第一个)。我已经为我创建的两个类(即Edge和Vertex)重写了一个equals方法,但是图表假设边缘是顶点是不同的并添加了所有这些。 这是输出:

Vertices:1,4,1,1,2,1,1,2,2,3
Edges:1#3[1,3] 1#4[1,4] 1#2[1,2] 1#2[1,2] 2#1[2,1] 

那么,我做错了什么?

PS。仅供参考我在这里创建的课程:

public class Vertex {

    private String id;
    //More info in the future

    public Vertex(String id){
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object obj){
        return ((Vertex) obj).id.equals(this.id);
    }

    @Override
    public String toString(){
        return this.id;
    }

}

public class Edge {

    private String id;
    private double weight;

    public Edge(String id, double weight){
        this.id = id;
        this.weight = weight;
    }

    public Edge(String id){
        this.id = id;
        this.weight = -1;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    @Override
    public boolean equals(Object obj){
        return ((Edge) obj).id.equals(this.id);
    }

    @Override
    public String toString(){
        return this.id;
    }

}

1 个答案:

答案 0 :(得分:2)

这是一个典型的Java问题,而不是JUNG特有的。基本上,你覆盖equals()但不覆盖hashCode(),所以你的哈希码不是“与equals()一致”。有关更多上下文和一些解决方案,请参阅此问题及其答案:How to ensure hashCode() is consistent with equals()?