【发布时间】:2020-04-11 17:37:03
【问题描述】:
我有这样的课:
class Vertex {
char v;
char w;
int cost;
public Vertex(char v, char w, int cost){
this.v = v;
this.w = w;
this.cost = cost;
}
@Override
public String toString(){
return "["+v+" "+w+" "+cost+"]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vertex vertex = (Vertex) o;
return (v == vertex.v && w == vertex.w) || (w == vertex.v && v == vertex.w);
}
@Override
public int hashCode() {
return Objects.hash(v, w);
}
}
我试图让equals() 在两个顶点相等或相反相等时返回 true。这意味着如果存在顶点 (v,w) 和 (w,v),它应该返回 true。
我的equals() 应该是对称和自反的,但对于 (v,w) 和 (w,v) 情况,set.contains() 仍然返回 false。
我将不胜感激。
【问题讨论】:
-
你试过调试你的代码吗?
-
HashSet的set.contains将与hashCode()(第一个)进行比较,并且您的顶点v,w和w,v具有不同的哈希码。 -
@ElliottFrisch 这很有道理,你知道我怎样才能让他们拥有相同的哈希码吗?
-
你可以试试
return v+w;
标签: java set equals contains hashset