contacts of Equals and Hashcode methods

It 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:

  1. reflexive
    a is an object,
    so if we call a.equals(a), the method should always return true
  2. symmetric
    a and b are different objects.
    If a.equals(b) returns true, b.equals(a) must return true as well and vice versa. If b.equals(a) returns false, a.equals(b) must return false.
  3. transitive
    a, b, c are different objects.
    If a.equals(b) returns true and b.equals(c) returns true, a.equals(c) must be true.
  4. 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, if a.equals(b) returns true, it will be true until a and b has not been changed.
  5. null
    a is an object.
    The result of a.equals(null) is always false.