【问题标题】:How do I prevent my graph from adding multiple custom edges? [duplicate]如何防止我的图表添加多个自定义边? [复制]
【发布时间】:2011-11-17 11:00:24
【问题描述】:

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

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

}

【问题讨论】:

标签: java vertex edges jung


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-01-19
    • 2023-04-08
    • 1970-01-01
    • 2010-10-14
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多