Tips for Implementing hashCode
You must override hashCode
in every class that overrides
equals
.
Tips for converting primitive types to int
:
boolean
:v ? 1 : 0
.byte
,char
, orshort
:(int) v
.long
:(int) (v ^ (v >>> 32))
.float
:Float.floatToIntBits(v)
.double
:Double.doubleToLongBits(v)
and then convert the result as above.null
: Usually use0
here.- Object reference:
- If
equals
is defined as a recursive function, computehashCode
recursively, too. - Otherwise, compute a “canonical representation” and then invoke
hashCode
on it.
- If
- Array: Treat it as if each element was a separate member field.
An okay hash function:
Write unit tests to verify that equal instances have equal hash codes.
You may cache the hash code of immutable objects.