Changing the elements in a set changes the 'equals' semantics

前端 未结 1 1667
我寻月下人不归
我寻月下人不归 2020-12-18 12:35

Imagine that we have this piece of code.

public class HashAddAfter {
    private class A {
        public int value;
        public A(int value) {
                   


        
相关标签:
1条回答
  • 2020-12-18 13:01

    This is exactly the expected behavior. There is no possible way for a Set implementation to be aware that the hashCode of an element has changed, so there's nothing it can do to defend against that possibility.

    From the Set Javadoc:

    Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.

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