hashCode方法的最佳实现 [英] Best implementation for hashCode method
问题描述
我们如何确定集合的最佳实现(code> hashCode()方法(假设equals方法已被正确覆盖)?
最佳实施?这是一个很难回答的问题,因为它取决于使用模式。
几乎所有情况下,合理的良好实现都在 Josh Bloch 的项目8(第二版)中的 有效Java 。最好的办法是在那里查找,因为作者解释了为什么这种方法很好。
短版
-
创建
int结果
并指定一个非零值值。 -
在
equals()中测试的每个字段
f
/ code>方法,计算一个哈希码c
:如果字段f是布尔值
:
计算(f?0:1)
; - 如果字段f是
字节
,char
,或
int
:calculate(int)f
; $ b $如果字段f是long
:calculate(int)(f ^(f>>> 32))
; - 如果该字段f是
浮
:计算Float.floatToIntBits( f)
; - 如果字段f是
double
:calculateDouble .doubleToLongBits(f)
并像每个一样处理返回值long value; - 如果字段f是一个对象:使用
hashCode()
方法或0如果f == null
; - 如果字段f是一个数组字段作为单独的元素,并以递归方式计算散列值,并按照下面的描述合并这些值。
-
结合散列值
c
和result
:结果= 37 *结果+ c
-
返回
结果
这应该导致适当的分配散列值适用于大多数使用情况。
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.
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.
A short version
Create a
int result
and assign a non-zero value.For every field
f
tested in theequals()
method, calculate a hash codec
by:- 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.
- If the field f is a
Combine the hash value
c
withresult
:result = 37 * result + c
Return
result
This should result in a proper distribution of hash values for most use situations.
这篇关于hashCode方法的最佳实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!