gpt4 book ai didi

java - 覆盖 hashCode() - 这够好了吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:24:02 25 4
gpt4 key购买 nike

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

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().

编辑:我更新了我的问题以包含一个long 字段。 longhashCode() 中应该如何处理?让它溢出int

最佳答案

您的哈希码确实满足以下属性:如果两个对象相等,则它们的哈希码需要相等。所以,以这种方式,它已经“足够好”了。但是,很容易在哈希码中产生冲突,这会降低基于哈希的数据结构的性能。

虽然我会稍微不同地实现它:

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

您应该查看 documentation for the hashCode() method 对象。它列出了哈希码必须满足的条件。

关于java - 覆盖 hashCode() - 这够好了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4442136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com