在第 4.3 章的 Hibernate 文档中。 “Implementing equals() and hashCode()”他们写了这句话:
"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."
我不明白它违反了什么契约以及它会带来什么问题。
最佳答案
HashSet
(由 HashMap
支持)在对象的哈希码不变时起作用。那是因为它根据哈希码保存它们。
因此,如果您将 hashCode()
基于标识符,并放置没有标识符的实体,它们都将具有相同的哈希码。其中,如果它们也 equal(..)
(它们将是),将不允许集合中有多个对象。
现在,如果该集合中有一些实体具有分配的标识符,而一个没有分配标识符(稍后保存),则该集合将具有错误的哈希码。
同时检查 this question对于 hashCode()
和 equals(..)
关于java - 在 Hibernate 中存储在 Set 中时的 equals() 和 hashCode(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5847272/