集合的 hashCode 方法的最佳实现 [英] Best implementation for hashCode method for a collection
问题描述
我们如何决定集合的 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 的 Effective Java 在第 8 项(第二版)中针对几乎所有情况提出了合理的良好实现.最好的办法是在那里查找,因为作者在那里解释了为什么这种方法是好的.
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 结果
并分配一个非零值.
对于在equals()
方法中测试的每个字段 f
,计算一个哈希码c
作者:
For every field f
tested in the equals()
method, calculate a hash code c
by:
- 如果字段 f 是
boolean
:计算(f ? 0 : 1)
; - 如果字段 f 是
byte
、char
、short
或int
:计算(int)f
; - 如果字段 f 是
long
:计算(int)(f ^ (f >>>32))
; - 如果字段 f 是
float
:计算Float.floatToIntBits(f)
; - 如果字段 f 是
double
:计算Double.doubleToLongBits(f)
并像处理每个 long 值一样处理返回值; - 如果字段 f 是 object:使用
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
结合:
Combine the hash value c
with result
:
result = 37 * result + c
返回结果
对于大多数使用情况,这应该会导致哈希值的正确分布.
This should result in a proper distribution of hash values for most use situations.
这篇关于集合的 hashCode 方法的最佳实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!