Java / Object, Class and Package
Good implementation of hashCode method in Java.
As per the expert's recommendation, the below steps are listed.
- Create a int
hashcodeResultand assign it a non-zero value. - For every field f tested in the equals method,calculates its hash code value
cusing the following.- If the field f is a boolean: calculate
(f ? 0 : 1); - If the field f is a byte, char, short or int: calculate (int)f;
- field f is a long, calculate
(int)(f ^ (f >>> 32)); - field f is a float, calculate
Float.floatToIntBits(f); - field f is a double, calculate
Double.doubleToLongBits(f)and use the long value; - If the field f is an object: Use the result of the hashCode() method or 0 if f == null;
- If the field f is an array, consider every field as separate element and calculate the hash value in a recursive fashion and combine the values.
- If the field f is a boolean: calculate
c with hashcodeResult. hashcodeResult=37+c+ hashcodeResult. hashcodeResult.More Related questions...