开发者

my HashSet contains (meaningfully equivalent) duplicates!

开发者 https://www.devze.com 2023-03-03 12:29 出处:网络
I\'ve overridden the hashCode() and equals() methods in my Person class so that two Person objects with the same name (a String) will be viewed as equal, but my set still contains two Persons with the

I've overridden the hashCode() and equals() methods in my Person class so that two Person objects with the same name (a String) will be viewed as equal, but my set still contains two Persons with the same name.

Here's the code开发者_JS百科 from my Person class:

public boolean equals(Person aPerson) {
    Person p = (Person) aPerson;
    //Since name is a String, we can just use
    //the overridden equals() method to ask
    //one name if it's equal to the other
    //person's name.
    return getName().equals(p.getName());
}

public int hashCode() {
    //Strings also have an overridden hashCode() method
    //so we can just return the result of calling hashCode()
    //on the name (instead of the object!)
    return name.hashCode();
}


Your equals method isn't overriding Object.equals(object), since it takes a Person as a parameter.

To avoid this issue, always add the @Override annotation when you override a method.
This way, you'll get an error if you get the parameters wrong.


Did the duplicate person object get added when it was equivalent, or did the person object get added when it was not a duplicate, and then modified so that it was a duplicate? The latter case is not defined for java.util.Set.

rc

0

精彩评论

暂无评论...
验证码 换一张
取 消