覆盖hashCode()-这样够好吗? [英] Overriding hashCode() - is this good enough?

查看:93
本文介绍了覆盖hashCode()-这样够好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个字段仅是原始字段的类,例如:

For a class whose fields are solely primitive, ex.:

class Foo
{
    int a;
    String b;
    boolean c;
    long d;

    boolean equals(Object o)
    {
        if (this == o) return true;
        if (!(o instanceof Foo)) return false;
        Foo other = (Foo) o;
        return a == other.a && b.equals(other.b) && c == other.c && d = other.d;
    }
}

这是否足够合理?编写 hashCode()的方式?

Is this a reasonably "good enough" way to write hashCode()?

boolean hashCode()
{
    return (b + a + c + d).hashCode();
}

也就是说,我构造了一个 String equals()使用的字段相同,然后仅使用 String#hashCode()

That is, I construct a String out of the same fields that equals() uses, and then just use String#hashCode().

编辑::我已更新问题,以包括字段。 long 应该如何在 hashCode()中处理?只是让它溢出 int

I've updated my question to include a long field. How should a long be handled in hashCode()? Just let it overflow int?

推荐答案

您的哈希码确实满足属性,如果两个对象相等,则它们的哈希码必须相等。因此,这样就足够了。但是,在哈希码中创建冲突非常简单,这会降低基于哈希的数据结构的性能。

Your hash code does satisfy the property that if two objects are equal, then their hash codes need to be equal. So, in that way it is 'good enough'. However, it is fairly simple to create collisions in the hash codes which will degrade the performance of hash based data structures.

我会稍微不同地实现它:

I would implement it slightly differently though:

public int hashCode() {
    return a * 13 + b.hashCode() * 23 + (c? 31: 7);
}

您应该签出 hashCode() 对象的方法。它列出了哈希码必须满足的条件。

You should check out the documentation for the hashCode() method of Object. It lays out the things that the hash code must satisfy.

这篇关于覆盖hashCode()-这样够好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆