In Hibernate documentation in chapter 4.3. "Implementing equals() and hashCode()" they wrote this sentence:
"Furthermore, if an instance is unsaved and currently in a Set, saving it will assign an identifier value to the object. If equals() and hashCode() are based on the identifier value, the hash code would change, breaking the contract of the Set."
I don't understand what contract it breaks and what problems can arrive from it.
a HashSet
(backed by HashMap
) works if the hashcodes of objects do not change. That's because it holds them based on their hashcodes.
Thus, if you base your hashCode()
on the identifier, and put entities without identifier, they will all have the same hash code. Which, if they are also equal(..)
(which they will be), will not allow more than one object in the set.
Now, if the set has some entities with assigned identifier and one without, which is later saved, then the set will have the wrong hashcode for it.
Also check this question for what are your options about hashCode()
and equals(..)
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