Hashcode and Equals for Hashset

Lolly picture Lolly · Mar 22, 2011 · Viewed 99.9k times · Source

Please clarify my doubt in Hashset. Consider the following code,

class Person
{
    String name;

    Person(String n)
    {
        name=n; 
    }
    public String getName()
    {
        return name;   
    }

    @Override
    public boolean equals(Object arg0) {

        System.out.println("in equals");

        Person obj=(Person)arg0;

        System.out.println("1st "+getName());
        System.out.println("2nd "+obj.getName());

        if(this.getName().equals(obj.getName()))
        {
                return true;
        }
        return false;
    }


    @Override
    public int hashCode() {

        System.out.println("in hash code");
        System.out.println(" value is "+Integer.valueOf(name.charAt(0)));
        return Integer.valueOf(name.charAt(0));
    }
}

in main I have the following code

Person obj1=new Person("bcd");

Person obj2=new Person("cde");

Person obj3=new Person("abc");

Person obj4=new Person("abc");

Now if I add these objects to hashset

Set<Person> sset=new HashSet<Person>();

sset.add(obj1);
sset.add(obj4);
sset.add(obj2);
sset.add(obj3);

I am getting this output

in hash code                                                                      
value is 98    
in hash code   
value is 97    
in hash code    
value is 99    
in hash code    
value is 97  
in equals  
1st abc     
2nd abc

Question 1 : why equals() function is called only once for checking obj3 and obj4 ? Why its not checked for rest of the objects ?

Question 2 : If the answer is because they both have same hash code,only then equals will be called, then why its not called for below code

sset.add(obj1);
sset.add(obj4);
sset.add(obj2);
sset.add(obj4);

output is :

in hash code  
value is 98  
in hash code   
value is 97   
in hash code   
value is 99   
in hash code  
value is 97 

It's not going inside equals() method even though two same objects are added to hash set which has same hash code.

Question 3 :I iterated the above value and printed the contents but neither hashcode nor equals were called. when its really useful to override hashcode and equals method ?

Question 4 : When will hashCode() and equals() be called?

Answer

Erik picture Erik · Mar 22, 2011
  1. There's no need to call equals if hashCode differs.
  2. There's no need to call hashCode if (obj1 == obj2).
  3. There's no need for hashCode and/or equals just to iterate - you're not comparing objects
  4. When needed to distinguish in between objects.