I have a class myDemoClass to store name and a class to put in a HashMap. While experimenting with overriding hashCode() method, the HashMap is returning null even if hashcodes are different. Why? I have overridden the hashCode() method so that different objects will have different hashcode even if having the same name value.
public class myDemoClass {
String name;
int value;
static int i=1;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int hashCode()
{
//return name.hashCode();//now the hashcode are same
return i++;//now the hashcode is different
}
public boolean equals(Object obj)
{
myDemoClass m=(myDemoClass)obj;
if(obj==this)
return true;
if(obj instanceof myDemoClass)
{
return getName().equals(m.getName());
}
return false;
}
}
public class Hashcodes {
myDemoClass m1=new myDemoClass();
myDemoClass m2=new myDemoClass();
HashMap h=new HashMap();
public boolean test()
{
m1.setName("s");
m2.setName("s");
System.out.println(m1.hashCode());
System.out.println(m2.hashCode());
h.put(m1, "a1");
h.put(m1, "b1");
System.out.println(h.get(m1));
System.out.println(h.get(m2));
System.out.println(h.get(m1));
return true;
}
public static void main(String args[])
{
Hashcodes h=new Hashcodes();
h.test();
}
}
Output with different hashcode:
1
2
null
null
null
Output with same hashcode:
115
115
b1
b1
b1