java - Best implementation for hashCode method -
how decide on best implementation of hashcode()
method collection (assuming equals method has been overridden correctly) ?
the best implementation? hard question because depends on usage pattern.
a cases reasonable implementation proposed in josh bloch's effective java in item 8. best thing there because author explains there why approach good.
a short version
create
int result
, assign non-zero value.for every field
f
tested inequals()
method, calculate hash codec
by:- if field f
boolean
: calculate(f ? 0 : 1)
; - if field f
byte
,char
,short
orint
: calculate(int)f
; - if field f
long
: calculate(int)(f ^ (f >>> 32))
; - if field f
float
: calculatefloat.floattointbits(f)
; - if field f
double
: calculatedouble.doubletolongbits(f)
, handle return value every long value; - if field f object: use result of
hashcode()
method or 0 iff == null
; - if field f array: see every field separate element , calculate hash value in recursive fashion , combine values described next.
- if field f
combine hash value
c
result
:result = 37 * result + c
return
result
this should result in proper distribution of hash values use situations.
Comments
Post a Comment