Hi i’m trying to learn the purpose of hashcode () and equals() method.I tried the following program.
import java.util.HashMap;
public class LearnHascode {
public String name;
public int age;
LearnHascode(String na)
{
name = na;
}
public int hashCode()
{
return name.hashCode();
}
public boolean equals(LearnHascode obj)
{
return this.name.equals(obj.name);
}
public static void main(String[] args)
{
HashMap h = new HashMap();
LearnHascode ob1 = new LearnHascode("Prabha");
LearnHascode ob2 = new LearnHascode("Prabha");
h.put(ob1, v1);
h.put(ob2, v2);
System.out.println(h);
System.(h.out.printlncontainsKey(new LearnHascode("Prabha")));
}
}
output :
{hash.LearnHascode@8ef7bdfc=Two, hash.LearnHascode@8ef7bdfc=one}
false
I have two doubts :
1) I thought HashMap will contain one entry as hascode of the two objects (ob1 and ob2) are same. could any one explain why there are two entries in the HashMap?
2) why System.(h.out.printlncontainsKey(new LearnHascode("Prabha"))); returns false?
Your
equals()method is wrong, and this breaks theHashMap. The argument toequals()is always anObject; you have to check what kind ofObjectit is and cast it in the body of the method.The
hashCode()value is used to sort the objects into categories, butequals()is used to decide whether two objects are actually the same. You need to define both of these methods correctly to getHashMapto work.