HashSet storing equal objects

痴心易碎 提交于 2019-12-05 15:07:38

This code doesn't do what you need it to:

public boolean equals(Dog d){
    return this.size.equals(d.size);
}

That's not overriding Object.equals, which is what HashSet uses. You need:

@Override
public boolean equals(Object d){ 
    if (!(d instanceof Dog)) {
        return false;
    }
    Dog dog = (Dog) d;
    return this.size.equals(dog.size);
}

Note that by using the @Override annotation, you're asking the compiler to verify that you're actually overriding a method.

EDIT: As noted, you also need to override hashCode in a way which is compatible with your equals method. Given that you're checking equality based on size, the simplest option would be:

@Override
public int hashCode() {
    return size.hashCode();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!