小编vol*_* dr的帖子

HashMap使用equals true和相同的hashcode添加对象

我正在尝试为其创建自定义对象HashMap并编写代码hashcodeequals方法.在添加对象时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)

java equals hashmap hashcode

4
推荐指数
1
解决办法
305
查看次数

标签 统计

equals ×1

hashcode ×1

hashmap ×1

java ×1