LoginSignup
1
1

More than 5 years have passed since last update.

組データに対する hashCode() の実装はどのようにすればいいですか?

Last updated at Posted at 2012-03-26

二つ組のデータで、(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();
    }
}

これは邪道でしょうか?なにか問題が起こりますか?
また、推奨されるやり方があれば教えてください。

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1