Friday, January 25, 2013

Hashcode and equals



Java.lang.Object has two methods:-
-          Public Boolean equals(Object o)
-          Public int hashCode()

  • These are heavily used with Collections.
  • Whenever it is invoked on the same object more than once during an execution, the hashCode() method must consistently return the same integer. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals() method, then calling the hashCode() method on each of the two objects should return the same integer.
  • Also It is not mandatory that if two objects are not equal according to the equals(java.lang.Object) method, then calling the hashCode() method on each of the two objects return distinct integer results.
  • It is necessary to override the hashCode() method whenever equals() method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
  • Sets use equals() to enforce non-duplicates, and HashSet uses hashCode() as a first-cut test for equality. Technically hashCode() isn't necessary then since equals() will always be used in the end, but providing a meaningful hashCode() will improve performance for very large sets or objects that take a long time to compare using equals().



No comments:

Post a Comment