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.
Create a int result
and assign a non-zero value.
For every field f
tested in the equals()
method, calculate a hash code c
by:
boolean
:
calculate (f ? 0 : 1)
;byte
, char
, short
or int
: calculate (int)f
;long
: calculate (int)(f ^ (f >>> 32))
;float
: calculate Float.floatToIntBits(f)
;double
: calculate Double.doubleToLongBits(f)
and handle the return value like every long value;hashCode()
method or 0 if f == null
;Combine the hash value c
with result
:
result = 37 * result + c
Return result
This should result in a proper distribution of hash values for most use situations.