hashcode and equals in java interview questions

Java interview question on hashcode() and equals() || Java collection interview questions on HASHMAP

Every time a new Integer object is created with same integer value passed; the Integer object will return the same hash value. Once the same hash value is returned, JVM will go to the same hashmap bucket every time and if in case there are more than one objects present for the same hash value it will use equals() method to identify the correct object.

hashcode() and equals() contracts:

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.
  • 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 used in equals comparisons on the object is modified. 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(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
  • Java HashMap:

    hashcode():You might know if you put entry in HashMap, first hashcode is calculated and this hashcode used to find bucket(index) where this entry will get stored in hashMap.You can read more at

    equals():You have to override equals method, when you want to define equality between two object. If you don’t override this method, it will check for reference equality(==) i.e. if tow reference refers to same object or not

    This country class have two basic attributes- name and population.Now create a class called “EqualityCheckMain.java”

    12345678910111213141516171819202122 packageorg.arpit.java2blog; publicclassCountry{ Stringname; longpopulation; publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publiclonggetPopulation(){ returnpopulation; } publicvoidsetPopulation(longpopulation){ this.population=population; } }

    When you run above program, you will get following output

    12345678910111213141516171819 packageorg.arpit.java2blog; publicclassEqualityCheckMain{ /** * @author arpit mandliya */ publicstaticvoidmain(String[]args){ Country india1=newCountry(); india1.setName(“India”); Country india2=newCountry(); india2.setName(“India”); System.out.println(“Is india1 is equal to india2:”+india1.equals(india2)); } }

    In above program, we have created two different objects and set their name attribute to “india”.Because both references india1 and india2 are pointing to different object, as default implementation of equals check for ==,equals method is returning false. In real life, it should have return true because no two countries can have same name.Now lets override equals and return true if two country’s name are same.Add this method to above country class:

    123 Isindia1 isequal toindia2:false

    and now run EqualityCheckMain.java againYou will get following output:

    123456789101112131415161718 @Override publicbooleanequals(Objectobj){ if(this==obj) returntrue; if(obj==null) returnfalse; if(getClass()!=obj.getClass()) returnfalse; Country other=(Country)obj; if(name==null){ if(other.name!=null) returnfalse; }elseif(!name.equals(other.name)) returnfalse; returntrue; }

    Now this is because overriden equals method return true if two country have same name. One thing to remember here, signature of equals method should be same as above.

    123 Isindia1 isequal toindia2:true

    When you run above program, you will see following output:

    1234567891011121314151617181920212223242526272829303132 packageorg.arpit.java2blog; import java.util.HashMap;import java.util.Iterator; publicclassHashMapEqualityCheckMain{ /** * @author Arpit Mandliya */ publicstaticvoidmain(String[]args){ HashMap<Country,String>countryCapitalMap=newHashMap<Country,String>(); Country india1=newCountry(); india1.setName(“India”); Country india2=newCountry(); india2.setName(“India”); countryCapitalMap.put(india1,“Delhi”); countryCapitalMap.put(india2,“Delhi”); Iterator countryCapitalIter=countryCapitalMap.keySet().iterator(); while(countryCapitalIter.hasNext()) { Country countryObj=countryCapitalIter.next(); Stringcapital=countryCapitalMap.get(countryObj); System.out.println(“Capital of “+countryObj.getName()+“—-“+capital); } }}

    Now you must be wondering even through two objects are equal why HashMap contains two key value pair instead of one.This is because First HashMap uses hashcode to find bucket for that key object, if hashcodes are same then only it checks for equals method and because hashcode for above two country objects uses default hashcode method,Both will have different memory address hence different hashcode.Now lets override hashcode method.Add following method to Country class

    1234 Capital of IndiaDelhiCapital of IndiaDelhi

    Now run HashMapEqualityCheckMain.java againYou will see following output:

    123456789 @Override publicinthashCode(){ finalintprime=31; intresult=1; result=prime *result+((name==null)?0:name.hashCode()); returnresult; }

    So now hashcode for above two objects india1 and india2 are same, so Both will be point to same bucket,now equals method will be used to compare them which will return true. This is the reason java doc says “if you override equals() method then you must override hashCode() method”

    123 Capital of IndiaDelhi

    FAQ

    Why do we need to override hashCode and equals method Java interview?

    You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object. hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

    What is the relation between equals and hashCode in Java?

    hashCode() and equals() contract

    The basic rule of the contract states that if two objects are equal to each other based on equals() method, then the hash code must be the same, but if the hash code is the same, then equals() can return false.

    What is difference between equals and hashCode in Java?

    The value returned by hashCode() is the object’s hash code, which is the object’s memory address in hexadecimal. equals() checks if the two object references are same. If two objects are equal then their hashCode must be the same, but the reverse is not true.

    Can equal objects have same hashCode?

    If two objects have the same hashcode then they are NOT necessarily equal. Otherwise you will have discovered the perfect hash function. But the opposite is true: if the objects are equal, then they must have the same hashcode .

    Related Posts

    Leave a Reply

    Your email address will not be published.