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


当前回答

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

其他回答

如果你对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),但工作方式相同。

我在arrays . deephashcode(…)周围使用了一个小包装器,因为它可以正确地处理作为参数提供的数组

public static int hash(final Object... objects) {
    return Arrays.deepHashCode(objects);
}

在Apache Commons Lang中,有效Java的hashcode()和equals()逻辑有一个很好的实现。签出HashCodeBuilder和EqualsBuilder。

最好使用Eclipse提供的功能,它做得非常好,您可以把精力和精力放在开发业务逻辑上。

对于简单类,通常最容易基于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()应该返回不同的值。