二つ組のデータで、(a, b) == (b, a) としたいとき、hashCode() の実装はどのようにすべきでしょうか?
今はこんな風にやっています。
MyCouple.java
public class MyCouple {
private final String left;
private final String right;
public MyCouple(String left, String right) {
this.left = left;
this.right = right;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MyCouple) {
MyCouple obj2 = (MyCouple) obj;
return ( this.left.equals(obj2.left) &&
this.right.equals(obj2.right) )
|| ( this.left.equals(obj2.right) &&
this.right.equals(obj2.left) );
}
return false;
}
@Override
public int hashCode() {
// これは邪道?
return left.hashCode() + right.hashCode();
}
}
これは邪道でしょうか?なにか問題が起こりますか?
また、推奨されるやり方があれば教えてください。