What is the Contract between equals and hashCode method?

What is the Contract between equals and hashCode method

What is the Contract between equals and hashCode method

What is the Contract between equals and hashCode method
  1. If two objects are equals by .equals() then their hashCode must be equals. That is two equivalent object should have the same hashCode that is if r1.equals(r2) is true then r1.hashcode==r2.hashcode is always true.
  2. Object class .equals() method and hashCode() method follows above contract hence whenever we are overriding .equals() method compulsory we should override hashCode() to satisfy above contract( that is two equivalent object should have same hash code).
  3. If two objects are not equal by .equals() method then there is no restriction on hashCode. Maybe equals or may not be equals.
  4. If hashCode of two objects is equal then we can’t conclude anything about .equals(). It may return true or false.
  5. If hashcode of two objects is not equal then these objects are always not equal by .equals method.
  • Note:- to satisfy contract between .equals() and hashCode() method whenever we are overriding .equals() methods compulsory we have to override hashCode() method otherwise we won’t get any compile time or runtime errors but it is not a good programming practice.
  • In string class .equals() is overridden for content comparison and hence hashCode() is also overridden to generate hashCode based on content.
String s1=new String("Samir");
String s2=new String("Samir");
System.out.println(s1.equals(s2)); //True
System.out.println(s1.hashCode()); //79650088
System.out.println(s2.hashCode()); //79650088
  • In StringBuffer .equals() method is not overridden for content comparison and hence hashCode also not overridden.
StringBuffer sb1=new StringBuffer("Samir");
StringBuffer sb2=new StringBuffer("Samir");
System.out.println(sb1.equals(sb2)); //False
System.out.println(sb1.hashCode()); //366712642
System.out.println(sb2.hashCode()); //1829164700

Note:-Based on which parameters we override .equals() method, it is highly recommended to use same parameters while overriding hashCode () method also. In all collection classes, In all wrapper classes, and in string class .equals is overridden for content comparison, hence it is highly recommended to override .equals() in over class also for content comparison.

Leave a Reply

Your email address will not be published. Required fields are marked *

*