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?
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With