The answer to this SO explains the issue I’m having: HashSet.remove() and Iterator.remove() not working
Basically, once I add something to the HashSet, if I modify any of its fields, then the set will fail any equality tests with a set containing an object with the exact same fields, since the hash code it was stored in was for when it had different fields set.
So, since that answer explains what’s going on, what would be a good workaround for this to have both the uniqueness of using a set and be able to modify internal fields of the objects in the set? Or is this just not possible?
Remove the object you want to modify from the set, change it, and then add it back. As far as I know there is no standard
Setimplementation that can cope with fields (that are used in either thehashCode()orcompareTo()implementation) being changed while it is stored.Alternatively, if the fields aren’t used in determining identity, equality or location (i.e. not used in
hashCode(),compareToorequals()) then there is no problem.