equals and hashcode methods contacts
It is well known that
equals() method is declared in
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
Both methods are extremely important for correct work with data structures based on hash algorithm such as
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:
a is an object,
so if we call
a.equals(a), the method should always return true
a and b are different objects.
b.equals(a)must return true as well and vice versa. If
a.equals(b)must return false.
a, b, c are different objects.
a.equals(b)returns true and
a.equals(c)must be true.
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, if
a.equals(b)returns true, it will be true until a and b has not been changed.
a is an object.
The result of
a.equals(null)is always false.