Skip to main content

Posts

Showing posts with the label hashCode()

Why always override hashcode() if overriding equals()?

In Java, every object has access to the equals() method because it is inherited from the Object class. However, this 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 can have unexpected repercussions when your class is in conjunction with all hash-based collections. Here is the contract, copied from the java.lang.Object specialization: public int hashCode() Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable . The general contract of hashCode is: 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 intege...