对于仅字段为原始字段的类,例如:
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();
}
也就是说,我从
String
使用的相同字段中构造了一个equals()
,然后仅使用String#hashCode()
。编辑:我已经更新了我的问题,以包括
long
字段。 long
应该如何在hashCode()
中处理?只是让它溢出int
吗? 最佳答案
您的哈希码确实满足以下属性:如果两个对象相等,则它们的哈希码必须相等。因此,以这种方式“足够好”。但是,在哈希码中创建冲突非常简单,这会降低基于哈希的数据结构的性能。
但我会稍微不同地实现它:
public int hashCode() {
return a * 13 + b.hashCode() * 23 + (c? 31: 7);
}
您应该 check out
hashCode()
的documentation for the Object
method。它列出了哈希码必须满足的条件。