I use HashSet and I need to modify the ID of an object, but it changes hashcode and breaks HashSet and rules of hashCode() method.
What is best solution: to delete object from Set and add object with new ID, or to keep the hash code (generated in constructor, for example) in every object in Set, or is there other way to solve this problem?
Thanks for help.
UPDATE: I made mistake: keeping hash code in object is terrible, because in that case equal objects can have different hash codes.
A HashSet as a container accesses its items (contains, remove) via the hash code of the items you put into it. The hash code is often built by the state of its instance members. So the hash code changes with the manipulation of the state of the object.
The documentation of Object says: "maintain the general contract for the hashCode() method, which states that equal objects must have equal hash codes"
As you noticed, if you change the state of an object you keep in a HashSet, the object can not longer be accessed by the remove method or found by the contains method of the HashMap.
The options you are offering are:
Remove the object, change it and add it again - works wonderful, easiest way if a HashSet is mandatory
Keep the value of the hash code 'somewhere' - Means, you have the same hash code for objects which are not equal. Or if you obey the documentation you can encounter two objects which are equals and have the same hash code, but their member variables differ! This can lead to unpredictable errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With