I am trying to create custom objects for HashMap
and have written code for hashcode
and equals
method. While adding objects in HashMap
, equals
method is true and hashcode
is returning same value for both objects yet HashMap
is adding both objects as different objects. How can this be possible?
Below is my code:
class B {
String name;
int id;
public B(String name, int id)
{
this.name=name;
this.id=id;
}
public boolean equals(B b){
if(this==b)
return true;
if(b==null)
return false;
if(this.name.equals(b.name) && this.id==b.id)
return true;
else
return false;
}
public int hashcode(){
return this.id;
}
public String toString(){
return "name: "+name+" id: "+id;
}
}
For testing above code, I have added following in my main class:
HashMap<B,String> sample=new HashMap<>();
B b1 = new B("Volga",1);
B b2 = new B("Volga",1);
System.out.println(b1.equals(b2));
System.out.println(b1.hashcode()+" "+b2.hashcode());
sample.put(b1, "wrog");
sample.put(b2,"wrog");
System.out.println(sample);
This is producing following output:
true
1 1
{name: Volga id: 1=wrog, name: Volga id: 1=wrog}
Can someone please explain why is this happening?