Always override hashcode() if overriding equals()

In Java, equals() is implemented in Object class by default. This method is used to compare two objects. The default implementation just simply compares the memory addresses of the objects. You can override the default implementation of the equals() method defined in java.lang.Object. If you override the equals(), you MUST also override hashCode(). Otherwise, a violation of the general contract for Object.hashCode() will occur, which results unexpected behavior when your class is in conjunction with all hash-based collections.

This is a general contract in java programming that “whenever you override equals(), override hashcode() also”.

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information...