A common source of bugs is the failure to override the hashCode method. You must override hashCode in every class that overrides equals. Failure to do so will result in a violating of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet and Hastable.
- Whenever it is invoked on the same object more than once during an execution of an application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need to remain consistent from one execution of application to another execution of the same application.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal to the equals(Object) method, then calling the hashCode method on each of the two Objects must produce distinct integer.
Equal objects must have equal hash codes
Two distinct instances may be logically equal according to a class’s equals method, but to Object’s hashCode method, they’re just two objects with nothing much in common.
public class ColorPoint { private final Point point; private final Color color; public ColorPoint(int x, int y, Color color) { if (color == null) throw new NullPointerException(); point = new Point(x, y); this.color = color; } /** * Returns the point-view of this color point */ public Point asPoint() { return point; } @Override public boolean equals(Object o) { if (!o instance of ColorPoint) { return false } ColorPoint cp = (ColorPoint) o; return cp.point.equals(point) && cp.color.equals(color); } } public final class PhoneNumber { private final short areaCode; private final short prefix; private final short lineNumber; public PhoneNumber(int areaCode, int prefix, int lineNumber) { rangeCheck(areaCode, 999, "area code"); rangeCheck(prefix, 999, "prefix"); rangeCheck(lineNumber, 9999, "line number"); this.areaCode = (short) areaCode; this.prefix = (short) prefix; this.lineNumber = (short) lineNumber; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instance of PhoneNumber)) return false; PhoneNumber pn = (PhoneNumber) o; return pn.lineNumber == lineNumber && pn.prefix == prefix && pn.areaCode = areaCode; } //Broken - no hashCode method! }
Suppose you attempt to use this class with a HashMap:
MapphoneNumberMap = new HashMap<>(); phoneNumberMap.put(new PhoneNumber(707, 867, 5309), "Jenny");
At this point, you might expect that phoneNumberMap.get(new PhoneNumber(707, 867, 5309)) to return “Jenny”, but it returns null. Notice that two PhoneNumber instances are involved: one is used for insertion into the HashMap, and a second, equal, instance is used for (attempted) retrieval.
A recipe for hashCode
- Store some constant nonzero value, say, 17, in an int variable called result.
- For each significant field f in your object (each field taken into account by the equals method) do the following:
- Compute an int hash code c for the field:
- If the field is boolean, compute (f ? 1 : 0)
- If the field is byte, char, short, or int, compute (int) f.
- If the field is long, compute (int) (f ^ (f >> 32))
- If the field is a float, compute Float.toFloatIntBits(f).
- If the field is a double, compute Double.doubleToLongBits(f) and then hash results long as in step 2.1.3.
- If the field is an object reference and this class’s equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If a more complex comparison os required, compute a “canonical representation” for this field and invoke hashCode on the canonical representation. If the value of the field is null, return 0 (or some other constant, but 0 is traditional).
- If the field is an array, treat it as if each element were separate field. That is, compute a hash code for each significant element by applying there rules recursively, and combine these values per step 2.2. If every element in an array field is significant, you can use one of the Arrays.hashCode methods added in release 1.5.
- Combine the hash code c computed in step 2.1 into result as follows: result = 31 * result + c;
- Return result
- When you are finished writing the hashCode method, ask yourself whether equals instances have equal hash codes. Write unit tests to verify your intuition!
- Compute an int hash code c for the field:
Do not be tempted to exclude significant parts of an object from the hash code computation to improve performance. While the resulting hash function may run faster, its poor quality may degrade hash tables performance to the point where they become unusably slow.