问题描述
在Hibernate文档的第4.3章中. "实现equals()和hashCode( )",他们写下了这句话:
In Hibernate documentation in chapter 4.3. "Implementing equals() and hashCode()" they wrote this sentence:
我不知道它会打破什么合同,以及由此会带来什么问题.
I don't understand what contract it breaks and what problems can arrive from it.
推荐答案
a HashSet
(由HashMap
支持)在对象的哈希码未更改的情况下有效.那是因为它根据它们的哈希码保存它们.
a HashSet
(backed by HashMap
) works if the hashcodes of objects do not change. That's because it holds them based on their hashcodes.
因此,如果您将hashCode()
基于标识符,并将没有标识符的实体放在一起,则它们都将具有相同的哈希码.如果它们也是equal(..)
(将是),则它们将不允许集合中有多个对象.
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.
还要检查这个问题是什么您关于hashCode()
和equals(..)
Also check this question for what are your options about hashCode()
and equals(..)
这篇关于在Hibernate中存储在Set中时,equals()和hashCode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!