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 use0here.- Object reference:
- If
equalsis defined as a recursive function, computehashCoderecursively, too. - Otherwise, compute a “canonical representation” and then invoke
hashCodeon it.
- If
- Array: Treat it as if each element was a separate member field.
An okay hash function:
// Initial value of code is usually non-zero, say 17.
code = 31 * code + hashValue;Write unit tests to verify that equal instances have equal hash codes.
You may cache the hash code of immutable objects.
