开发者

How do I prevent my graph from adding multiple custom edges? [duplicate]

This question already has answers here: How to ensure hashCode() is consistent with equals()? (8 answers) Closed 3 years ago.

I have defined a custom edge and vertex type to use in an undirected sparse graph. The problem is that the graph is adding multiple edges which I don't want. For instance, considering the code below:

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"));

I've intentionally added two similar edges (the first ones). I've overrided an equals method for both classes I've created, i.e, Edge and Vertex, but the graph assumes as the edges as the vertices are differents and adds all of them. Here's the output:

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] 

So, what am I doing wrong?

PS. FYI here are the classes I've created:

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;
    }

}


This is a classic Java problem, and not JUNG-specific. Basically, you overrode equals() but not hashCode() and so your hashcodes are not "consistent with equals()". See this question and its answers for more context and some solutions: How to ensure hashCode() is consistent with equals()?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜