我们如何决定集合的hashCode()方法的最佳实现(假设equals方法已被正确重写)?


当前回答

使用Apache Commons EqualsBuilder和HashCodeBuilder上的反射方法。

其他回答

首先确保equals被正确实现。摘自一篇IBM DeveloperWorks文章:

对称性:对于两个参考,a和b,当且仅当b等于(a)时,a等于(b) 自反性:对于所有非空引用,a.equals(a) 及物性:如果a等于(b) b等于(c),那么a等于(c)

然后确保它们与hashCode的关系尊重联系人(来自同一篇文章):

与hashCode()的一致性:两个相等的对象必须具有相同的hashCode()值

最后,一个好的哈希函数应该努力接近理想的哈希函数。

对于简单类,通常最容易基于equals()实现检查的类字段实现hashCode()。

public class Zam {
    private String foo;
    private String bar;
    private String somethingElse;

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        Zam otherObj = (Zam)obj;

        if ((getFoo() == null && otherObj.getFoo() == null) || (getFoo() != null && getFoo().equals(otherObj.getFoo()))) {
            if ((getBar() == null && otherObj. getBar() == null) || (getBar() != null && getBar().equals(otherObj. getBar()))) {
                return true;
            }
        }

        return false;
    }

    public int hashCode() {
        return (getFoo() + getBar()).hashCode();
    }

    public String getFoo() {
        return foo;
    }

    public String getBar() {
        return bar;
    }
}

最重要的是保持hashCode()和equals()的一致性:如果equals()对于两个对象返回true,那么hashCode()应该返回相同的值。如果equals()返回false,那么hashCode()应该返回不同的值。

使用Apache Commons EqualsBuilder和HashCodeBuilder上的反射方法。

我更喜欢使用实用工具方法从谷歌集合库从类对象,帮助我保持我的代码干净。equals和hashcode方法通常都是从IDE的模板中创建的,所以它们的可读性不太好。

如果你对dmeister推荐的Effective Java实现感到满意,你可以使用一个库调用来代替自己的调用:

@Override
public int hashCode() {
    return Objects.hash(this.firstName, this.lastName);
}

这需要Guava (com.google.common.base.Objects.hashCode)或Java 7中的标准库(Java .util. objects .hash),但工作方式相同。