更新时间:2023-02-05 21:49:24
如果我比较两个A的实例而不覆盖equals方法,我会得到预期的结果吗? / p>
这取决于你的期望:)
默认实现将给出你引用相等 - 换句话说,当你比较两个引用时, equals
只有在它们引用同一个对象时才会返回true。 / p>
您通常会覆盖等于
来实现值相等 - 其中两个不同的对象被认为是相等的,通常是通过美德具有相等的字段值本身。相等的确切含义取决于您的设计 - 例如,两个对象仍然可以通过其他方式区分。
如果覆盖等于
,你应该也覆盖 hashCode
以与等于
一致>,如果 a.equals(b)
为真,那么 a.hashCode()== b.hashCode()
。这将允许您的类的实例用作基于散列的集合中的键(例如 HashMap
),以便您可以根据等于原始的,而不是必须使用对完全原始密钥对象的引用。
Possible Duplicate:
Overriding equals and hashCode in Java
If I have
class A {
int x = 1;
}
...
A a1 = new A();
A a2 = new A();
a1.equals(a2);
If I compare 2 instances of A without override the equals method, will I get expected result?
If I compare 2 instances of A without override the equals method, will I get expected result?
That depends on what you expect :)
The default implementation will give you reference equality - in other words, when you compare two references, equals
will only return true if they're references to the same object.
You would normally override equals
to implement "value equality" - where two distinct objects are deemed equal, usually by virtue of having equal field values themselves. The exact meaning of equality will depend on your design - the two objects could still be distinguishable in other ways, for example.
If you override equals
, you should also override hashCode
to be consistent with equals
, such that if a.equals(b)
is true, then a.hashCode() == b.hashCode()
. This will allow instances of your class to be used as keys in hash-based collections (e.g. HashMap
) so that you can look up a value based on a key which is equal to the original one, rather than having to use a reference to the exact original key object.