作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
对于一个字段完全是原始字段的类,例如:
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
字段。 long
在hashCode()
中应该如何处理?让它溢出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/
我是一名优秀的程序员,十分优秀!