我正在尝试为其创建自定义对象HashMap并编写代码hashcode和equals方法.在添加对象时HashMap,equals方法为true并且hashcode为两个对象返回相同的值,而HashMap将两个对象添加为不同的对象.这怎么可能?以下是我的代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
为了测试上面的代码,我在我的主类中添加了以下内容:
HashMap<B,String> sample=new HashMap<>();
B b1 = new B("Volga",1);
B b2 = new B("Volga",1); …Run Code Online (Sandbox Code Playgroud)