加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 覆盖hashCode() – 这还不错吗?

发布时间:2020-12-15 00:47:20 所属栏目:Java 来源:网络整理
导读:对于其字段仅为原始的类,例如: 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 == othe
对于其字段仅为原始的类,例如:
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()吗?

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

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

编辑:我已经更新了我的问题以包含一个长字段.应该如何在hashCode()中处理多长时间?只是让它溢出int?

解决方法

您的哈希代码确实满足以下属性:如果两个对象相等,则它们的哈希码必须相等.所以,通过这种方式,它“足够好”.但是,在哈希码中创建冲突相当简单,这会降低基于哈希的数据结构的性能.

我会以稍微不同的方式实现它:

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

你应该看看对象的documentation for the hashCode() method.它列出了哈希码必须满足的内容.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读