Always override hashCode when you override equals

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.

Suppose you attempt to use this class with a HashMap:

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

  1. Store some constant nonzero value, say, 17, in an int variable called result.
  2. For each significant field f in your object (each field taken into account by the equals method) do the following:
    1. Compute an int hash code c for the field:
      1. If the field is boolean, compute (f ? 1 : 0)
      2. If the field is byte, char, short, or int, compute (int) f.
      3. If the field is long, compute (int) (f ^ (f >> 32))
      4. If the field is a float, compute Float.toFloatIntBits(f).
      5. If the field is a double, compute Double.doubleToLongBits(f) and then hash results long as in step 2.1.3.
      6. 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).
      7. 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.
    2. Combine the hash code c computed in step 2.1 into result as follows: result = 31 * result + c;
    3. Return result
    4. When you are finished writing the hashCode method, ask yourself whether equals instances have equal hash codes. Write unit tests to verify your intuition!

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.

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest sit folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.