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
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.