Sunday, March 1, 2015

hashCode() and equals() method in Java

Work in progress:



hashCode() and equals() methods are defined in Object class and so all java objects inherit a default implementation of these two methods.

equals() simply checks for equality of two objects. The default implementation just checks for the object references of two objects to verify their equality.

hashCode() returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by implementation of Map interface.  The general contract of hashCode() is
  1. Calling hashCode() on the same method multiple times should return the same hashCode value each and every single time. (provided no information used in equals comparisons on the object is modified.) This integer need not be consistent across different executions of the application.
  2. If two objects are equal as per the equals() method, then both of them should return the same integer value.
  3. It is not necessary that two unequal objects as per equals() method will produce two distinct integer results. (However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.)

No comments:

Post a Comment