Java:如果存在相同参数的对象,则不添加新对象

Bob*_*y S 1 java constructor object

这是我的对象构造函数

static class Edge {
    int source; // source node
    int destination; // destination node
    int weight; // weight of the edge
    int predecessor; // previous node
    public Edge() {};
    public Edge(int s, int d, int w) { source = s; destination = d; weight = w; }
}
Run Code Online (Sandbox Code Playgroud)

现在,这是我创建一个新Edge对象的语句

edges.add(new Edge(nodeStart, tempDest, tempWeight));
Run Code Online (Sandbox Code Playgroud)

如果已经有一个使用相同参数创建的对象(nodeStart,tempDest),我需要跳过该语句

基本上,我不想两次添加相同的边.

edges.add(new Edge(0, 1, tempWeight));
edges.add(new Edge(0, 1, tempWeight));
Run Code Online (Sandbox Code Playgroud)

如果发生这种情况,我想确保它只添加一次,而不是新的相同对象.

jjn*_*guy 11

正确的方法是做edges一个Set<Edge>.然后正确覆盖hashcode和equals.

所以,你应该edges如此声明:

Set<Edge> egdes = new HashSet<Edge>();
Run Code Online (Sandbox Code Playgroud)

你应该实现hashCode和equals,如下所示:

public boolean equals(Object o) {
    if (o == null) return false;
    if (o == this) return true;
    if (!(o instanceof Edge)) return false;
    Edge oEdge = (Edge) o;
    return this.source == oEdge.source && 
           this.destination == oEdge.destination && 
           this.weight == oEdge.weight;
}

public int hashCode(){
    return source * 3 + dest * 11 + weight * 13;
}
Run Code Online (Sandbox Code Playgroud)

您应该阅读正确实现equals和hashCode的内容.我的例子并不好.但总的想法是传达的.