Equality – Part 3
September 23rd, 2008
There is still one final aspect of the equals() method that warrants mention. The rule is simple: when overriding the default equals() method, the hashCode() method must also be overridden.
The simplest explanation for the hashCode() method can be found in the Java API under its base implementation in the Object class:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects.
In other words, this method will return an int that is unique for what that particular instance represents. Again, as with equals, the important attributes in the class are used to determine the object’s uniqueness; the idea is that the uniqueness mimics the uniqueness of the real life entity represented by the instance.
There is an important phrase in that description: “reasonably practical”. Keep in mind there is a limit on the range of the int variable. However, it is conceivable that we would model something with a much greater range than that of int. For instance, if we were simply modeling people, it’s possible we would surpass the number supported by the full range of ints.
The hashCode method is typically used by Java collections when determining uniqueness. For instance, a Java Set guarantees the uniqueness of its elements. In other words, if I add the same object three times, the size of the set will still be 1. In order to guarantee this behavior, the Set implementation will use the hashCode method.
It should be obvious why hashCode and equals must be implemented as a pair. The equals method will be using attributes that guarantee its uniqueness. Therefore, we need the same uniqueness contract on the hashCode implementation.
Take the following code:
1 2 3 4 5 | Person p1 = new Person("Jason"); Person p2 = new Person("Jason"); p1.equals(p2); p1.hashCode() == p2.hashCode(); |
If we implement the equals method to take the name into account, the above check will return that they are equal. However, if we forget to override the hashCode method at the same time, it will continue to use object references in its calculation. Since these are different objects, this will return two different hash codes. Thus we have the equals method comparing the object’s logical equality while the hashCode method uses object references.
Previously, I mentioned how IDEs, such as IntelliJ, will generate the equals method. Many IDEs will automatically generate the hashCode at the same time, using the same values, to ensure the integrity of these two methods.
Read the rest of this series:

