java.util.Set.remove(Object o) - problem

后端 未结 2 1523
再見小時候
再見小時候 2020-12-18 09:32

I must be missing something here... I have the following code and output. Can you see why Category categoryToBeDeleted is not being deleted from the category se

相关标签:
2条回答
  • 2020-12-18 10:19

    Your set is actually a HashSet. Category isn't implementing hashCode. As a result, when you go to remove the object, the object identifier is used as the hash code, and for each different object, even if it's semantically equivalent, it ends up using a different hash code, looking in the wrong place in the hash set and not finding the appropriate matching object.

    Add

    @Override
    public int hashCode() {
        return id.hashCode();
    }
    

    to Category and all should be well.

    The requirement to override hashCode can be read in the JavaDoc for java.lang.Object#equals:

    Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

    As this text implies, the JavaDoc for hashCode covers this in more detail.

    Whilst the JavaDoc for remove could perhaps be clearer on the subject, it only references equals as part of the specification for which object it will remove - it doesn't say that equals is the only thing it will use.

    Finally, if you're using Eclipse, there's a warning you can turn on which will warn you if you override equals without overriding hashCode or vice-versa.

    0 讨论(0)
  • 2020-12-18 10:25

    If you override equals(), you should override hashCode() also.

    0 讨论(0)
提交回复
热议问题