Friday, June 30, 2017

equals() and hashCode() in Java


Collections such as HashMap and HashSet use the hashcode value of an object to determine how the object should be stored in the collection, and the hashcode is used again to help locate the object in the collection.
Hashing retrieval is a two-step process.
1.      Find the right bucket (using hashCode())
2.      Search the bucket for the right element (using equals() )

Here is a small example why we should overrride equals() and hashcode().Consider an Person  class which has two fields age and name.
public class EqualsClass {
      public static void main(String[] args) {
            Person p1 = new Person(1, "Paras");
            Person p2 = new Person(1, "Sonal");

            /*Equality basis on only roll num and not name*/
            System.out.println(p1.equals(p2));
            System.out.println(p1.hashCode());
            System.out.println(p2.hashCode());
           
            HashMap<Person, String> map = new HashMap<>();
            map.put(p1, "HELLOP1");
           
            /*Overriding equals() and Without Overriding hashCode()*/
            System.out.println(map.get(p1));
            System.out.println(map.get(p2));
           
            /*Although not added, still its there*/
            System.out.println(map.containsKey(p2));

            /*Overriding both equals() and hashCode()*/
            System.out.println(map.get(p1));
            System.out.println(map.get(p2));

      }
}

class Person {
      int rollnum;
      String name;

      public Person(int rollnum, String name) {
            super();
            this.rollnum = rollnum;
            this.name = name;
      }

      public boolean equals(Object obj) {
            if (obj instanceof Object && ((Person) obj).getRollnum() == this.rollnum)
                  return true;
            else
                  return false;
      }

      public int hashCode() {
            return rollnum * 100;
      }

      public int getRollnum() {
            return rollnum;
      }

      public void setRollnum(int rollnum) {
            this.rollnum = rollnum;
      }
}

OUTPUT

WITHOUT OVERRIDING hashCode()

true
2018699554
1311053135
HELLOP1
null
false
HELLOP1
null

WITH OVERRIDING hashCode()

true
100
100
HELLOP1
HELLOP1
true
HELLOP1
HELLOP1


No comments:

Post a Comment