A HashSet as a container accesses its elements (contains, deletes) through the hash code of the elements that you insert into it. A hash code is often built from the state of its instances. Thus, the hash code is changed by manipulating the state of the object.
The Object documentation says: "maintain a common contract for the hashCode () method, which states that equal objects must have the same hash codes"
As you noticed, if you change the state of an object stored in a HashSet, the object can no longer be accessed by the delete method or found using the contains method of the HashMap.
Options offered by you:
Delete the object, modify it and add it again - works great, easiest if HashSet is required
Keep the hash value somewhere. So you have the same hash code for objects that are not equal. Or, if you obey the documentation, you may come across two objects that are equal and have the same hash code, but their member variables are different! This can lead to unpredictable errors.
source share