如何在Scala中比较两个对象的相等性? [英] How to compare two objects for equality in Scala?
问题描述
我在两个对象之间进行了非常基本的相等性检查,但失败了.
I have a very basic equality check between two objects but it fails.
package foo
import org.junit.Assert._
object Sandbox extends App{
class A
val a = new A
val b = new A
assertEquals(a, b)
}
我的用例比较复杂,但是我想弄清楚我的基础知识.运行代码时出现断言错误:
My use-case is more complex but I wanted to get my basics right. I get an assertion error when I run the code:
Caused by: java.lang.AssertionError: expected:<foo.Sandbox$A@3f86d38b> but was:<foo.Sandbox$A@206d63fd>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:743)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
. . . .
如何比较两个对象是否相等?
How can I compare two objects for equality?
推荐答案
不幸的是,java在每个对象上定义了equals
,hashCode
和toString
方法. equals
的默认实现是检查引用相等性,即它们检查您所引用的对象是否完全相同.由于您创建了两个不同的对象,并且没有为A
提供equals方法,因此它们不是相等的,因为它们不是同一实例.
Unfortunately java defined an equals
a hashCode
and a toString
method on every object. The default implementation of equals
is to check referential equality, that is that they check that you are referring to the exact same object. Since you created two different objects, and gave no equals method to A
they are not equal, since they aren't the same instance.
您可以为A
提供更好的equals
方法,但是无论何时您覆盖equals
时,您也都应该覆盖hashCode
,以确保两者一致.他们达成一致的规则是:
You can provide A
with a better equals
method, but anytime you override equals
you should override hashCode
as well to ensure that they two are in agreement. The rules for them being in agreement are:
- 如果equals返回true,则两个对象必须返回相同的hashCode
- 如果对象具有不同的hashCode,则equals必须返回false.
这篇关于如何在Scala中比较两个对象的相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!