或等于哈希码的子句

时间:2014-07-15 13:42:13

标签: java equals hashcode

我有一个有两个成员的班级,a和b。 class和equals实现如下:

public static class Test {
    protected int a;
    protected int b;

    public boolean equals(final Object o) {
        if (o == this) {
            return true;
        } else if (o instanceof Test) {
            final Test t = (Test) o;

            return a == t.a || b == t.b;
        }
        return false;
    }
}

如何编写有效的哈希码函数?

感谢。

2 个答案:

答案 0 :(得分:3)

我认为唯一能满足与hashcode()实现的equals / hashcode契约的equals(Object)方法是一个返回常量的方法。


与其他人一样,我不明白你为什么要用这些语义定义equals方法。除此之外,您已将等式定义为不可传递:

X.equals(Y) && Y.equals(Z) does not imply X.equals(Z)

答案 1 :(得分:0)

如果你想要自己的哈希码,试试这个

    int hash = 3;
    hash = 7 * hash + a;
    hash = 7 * hash + b;

但是我应该使用Apache Utilis的hashCodeBuilder

顺便说一句

return a == t.a || b == t.b;
你确定吗?