我想定義一個Pair類,其中< 2,3>和< 3,2>是同一件事。平等的方法被覆蓋,但我不知道如何重寫hashcode函數來匹配。我到目前爲止的代碼是:雙對象重寫等於使反向對也相同
Set<Pair> edgePairs=new HashSet<>();
edgePairs.add(new Pair(2,3));
edgePairs.add(new Pair(2,4));
edgePairs.add(new Pair(2,5));
edgePairs.add(new Pair(4,2));
edgePairs.add(new Pair(2,3));
edgePairs.add(new Pair(3,2));
for (Pair edgePair : edgePairs) {
System.out.println(edgePair.x+" "+edgePair.y);
}
輸出:
2 3
2 4
2 5
4 2
3 2
正確的輸出不應該包含對< 4,2>和< 3,2>
對類:
public class Pair
{
int x, y;
public Pair(int x, int y) {
this.x = x; this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair that = (Pair) o;
if ((x == that.y && y == that.x)||(x == that.x && y == that.y))
return true;
return false;
}
@Override
public int hashCode() {
int result = x; result = 31 * result + y;
return result;
}
}
您的代碼看起來不正確。如果兩個對象之間的equals爲真,請確保哈希碼總是返回相同的結果。 – dabaicai