Changing values in HashSet

前端 未结 3 2069
滥情空心
滥情空心 2020-12-29 15:20

I\'ve read this question: Changing the elements in a set changes the \'equals\' semantics

However, I don\'t know how to solve the problem that I can\'t change an ite

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 16:03

    When you add testElement to the HashSet, it selects a bucket based on the hash code for testElement. When you ask the HashSet if it contains a TestElement, it computes the hash code of the object that it's looking for and searches only in that bucket.

    As your hashCode() is based on non-final field, the hash code can change behind the scenes of the HashSet. Thus completely invalidating the basic assumption of the HashSet.

    A correct implementation for the Testclass would have the s1 field as final.

提交回复
热议问题