什么时候应该覆盖Equals功能? [英] when should I override Equals function?
问题描述
<强>可能重复:强>结果,
Java:总是覆盖等于?
我应该覆盖 equals
我创建的任何类的函数?
should I override equals
function for any class that I create?
即使是非常简单的类,只包含一些非常简单的属性,而等于我需要它的每一个属性都相等?
even for very simple classes which only contains some very simple attributes and by equals I need every single attribute of it to be equal?
推荐答案
我应该为我创建的任何类重写equals函数吗?
should I override equals function for any class that I create?
覆盖等于
if(且仅限于)对象代表一些数据,即如果它模拟诸如 Person
, Car
或 RecipieIngredient
(这些通常最终出现在集合中等)。不要为其他类型的类重写equals,例如 LoginServlet
或 DatabaseUtil
。
Override equals
if (and only if) the object "represents some data", i.e. if it models something such as Person
, Car
or RecipieIngredient
(these typically end up in collections etc). Don't override equals for other types of classes, for example LoginServlet
or DatabaseUtil
.
每当覆盖等于
时,请记住始终覆盖 hashCode
。
Remember to always override hashCode
whenever you override equals
.
(一个自然的后续问题:) 如果我不重写equals和hashCode会怎样?
(A natural follow-up question:) What happens if I don't override equals and hashCode?
任何两个对象都将被视为不等,除非它们是完全相同的对象。
Any two objects will be considered unequal unless they are the exact same object.
[...]我需要它的每个属性都相等吗?
[...] I need every single attribute of it to be equal?
通常是。这取决于你如何定义你的平等概念。请注意,对于引用类型,您可以重用/委托 对象实现等于
(和 hashCode
)实施自己的。
Typically yes. It depends on how you define your notion of equality. Note that for reference types, you can reuse/delegate to that objects implementation of equals
(and hashCode
) when implementing your own.
相关问题:
- why we need to override equals and hashcode in java and why cannot we use Object class implementation
- Why do I need to override the equals and hashCode methods in Java?
这篇关于什么时候应该覆盖Equals功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!