问题描述
我们如何决定集合的 hashCode()
方法的最佳实现(假设已正确覆盖equals方法)?
How do we decide on the best implementation of hashCode()
method for a collection (assuming that equals method has been overridden correctly) ?
推荐答案
最佳实施方案?这是一个难题,因为它取决于使用模式。
The best implementation? That is a hard question because it depends on the usage pattern.
对于几乎所有情况,在 Josh Bloch 中提出了合理的良好实施第8项(第二版)中的 有效Java 。最好的方法是在那里查找,因为作者解释了为什么这种方法很好。
A for nearly all cases reasonable good implementation was proposed in Josh Bloch's Effective Java in Item 8 (second edition). The best thing is to look it up there because the author explains there why the approach is good.
-
创建
int结果
并指定非零值。
对于每个字段 f
在中测试等于()
方法,通过以下方式计算哈希码 c
:
For every field f
tested in the equals()
method, calculate a hash code c
by:
- 如果字段f是
布尔值
:
计算(f?0:1)
; - 如果字段f是
字节
,字符
,短
或int
:计算(int)f
; - 如果字段f是
long
:calculate(int)(f ^(f>>> 32))
; - 如果字段f是
float
:计算Float.floatToIntBits( f)
; - 如果字段f是
double
:计算Double .doubleToLongBits(f)
并像每一个一样处理返回值long值; - 如果字段f是对象:使用
hashCode()的结果
方法或0如果f == null
; - 如果字段f是数组:请参阅每个字段作为单独的元素,并以递归方式计算哈希值并组合下面描述的值。
- If the field f is a
boolean
:calculate(f ? 0 : 1)
; - If the field f is a
byte
,char
,short
orint
: calculate(int)f
; - If the field f is a
long
: calculate(int)(f ^ (f >>> 32))
; - If the field f is a
float
: calculateFloat.floatToIntBits(f)
; - If the field f is a
double
: calculateDouble.doubleToLongBits(f)
and handle the return value like every long value; - If the field f is an object: Use the result of the
hashCode()
method or 0 iff == null
; - If the field f is an array: see every field as separate element and calculate the hash value in a recursive fashion and combine the values as described next.
将哈希值 c
与结果
组合:
result = 37 * result + c
返回结果
这应该会导致正确的分发大多数使用情况下的哈希值。
This should result in a proper distribution of hash values for most use situations.
这篇关于集合的hashCode方法的最佳实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!