Wednesday, September 5, 2012

Why to override Hashcode in java?

Understand hashCode() and equals() in HashMap
Look at the below given Example:

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class HCode {
 public static void main(String[] args) {
  Map m = new HashMap();
  
  TestHC s1 = new TestHC("Sunday");
  TestHC s2 = new TestHC("Monday");
  TestHC s3 = new TestHC("Sunday");
  
  System.out.println("First object:-");
  m.put(s1, "Sunday");
  System.out.println("\n Second object:-");
  m.put(s2, "Monday");
  System.out.println("\n Third object:-");
  m.put(s3, "Sunday");
  System.out.println("\n Map size :-"+m.size());
  System.out.println("\n Map :- "+m.toString());
  
 }
}

class TestHC{
 String day;
 TestHC(String d) { day = d; }
   public boolean equals(Object o) {
       System.out.println("**calling equals()**");
      return ((TestHC)o).day == this.day;
   }
 
   /* public int hashCode() { 
      System.out.println("**calling hashcode()**");
     return new Date().getDay()+1;
    }*/

}


Output:
First object:-

Second object:-

Third object:-

Map size :-3

Map :- {TestHC@addbf1=Monday, TestHC@42e816=Sunday, TestHC@19821f=Sunday}

In the above code we commented the hashcode method and there is no call
for equals method,now if you check the output you will see map contain 
three elements/Objects which is wrong since the key of two of our object
is same that's "Sunday".

Now just uncomment the hashcode method and run the program the output is:

First object:-
**calling hashcode()**

 Second object:-
**calling hashcode()**
**calling equals()**

 Third object:-
**calling hashcode()**
**calling equals()**
**calling equals()**

 Map size :-2
**calling hashcode()**
**calling hashcode()**

 Map :- {TestHC@4=Monday, TestHC@4=Sunday}

Here you can see the equals and hashcode methods are called and the 
same key elements/Objects are removed the output itself tell's you 
what exactly happen.

Note:-
1. Find the right bucket - hashCode()
2. Search the bucket for the right element - using equals()

 

No comments:

Post a Comment