Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equals() and hashCode() when storing in a Set, in Hibernate

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.

like image 307
Daniel Avatar asked Dec 28 '22 21:12

Daniel


1 Answers

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(..)

like image 97
Bozho Avatar answered Dec 30 '22 09:12

Bozho