Java: change identifier changing hashcode

I use a HashSet and I need to change the identifier of the object, but it changes the hashcode and interrupts the HashSet and the rules of the hashCode () method.

What is the best solution: remove the object from the set and add the object with a new identifier or save the hash code (for example, generated in the constructor) in each object in Set or is there another way to solve this problem?

Thanks for the help.

UPDATE: I made a mistake: saving the hash code in the object is terrible, because in this case equal objects can have different hash codes.

+4
source share
1 answer

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.

+7
source

All Articles