contacts of Equals and Hashcode methods
📅 01 Jan 2019 🕑 About 1 min readIt is well known that equals()
method is declared in java.lang.Object
class.
It has a naive implementation that compares references of two objects and in case
if they are the same it returns true otherwise false.
There are many situations when we need to override this method. If you want your program works in way you expected, you should follow some contracts.
One of them is related to the companion of equals()
method. It is hashCode()
method.
Both methods are extremely important for correct work with data structures based on hash algorithm such as java.util.HashMap
or java.util.HashSet
.
The rule for overriding is simple. If equals method returns true for 2 objects, it means that hashCode should return the same value,
but equality of hash codes does not mean that objects are the same.
The last part of the statement is explained by hash collision.
It is not only thing that you should do. There is one more contact. According to it, your implementation of equals method should be:
- reflexive
Given:
a is an object,
so if we calla.equals(a)
, the method should always return true - symmetric
Given:
a and b are different objects.
Ifa.equals(b)
returns true,b.equals(a)
must return true as well and vice versa. Ifb.equals(a)
returns false,a.equals(b)
must return false. - transitive
Given:
a, b, c are different objects.
Ifa.equals(b)
returns true andb.equals(c)
returns true,a.equals(c)
must be true. - consistent
The result of invocation does not depend on how many times we call a method until we do not change the state of objects. In other words, ifa.equals(b)
returns true, it will be true until a and b has not been changed. - null
Given:
a is an object.
The result ofa.equals(null)
is always false.