Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why assertEquals(new int[]{1}, new int[]{1}) results in failure?

I was testing my shuffling class and came across one issue I cannot understand. Why does the following assert statement:

assertEquals(new int[]{1}, new int[]{1}); 

results in an AssertionError? Naturally, the correct answer is "because they are not equal!", but could someone explain me why? And how to test a method, for which I would like the two such objects to be equal?

like image 277
Marta Karas Avatar asked Nov 18 '25 22:11

Marta Karas


1 Answers

but could someone explain me why

Sure - arrays don't override equals, therefore they inherit the behaviour from Object, where any two distinct objects are non-equal.

It's even simpler than the version you showed if you use a 0-element array:

System.out.println(new int[0].equals(new int[0])); // false

That's why when checking for equality in non-test code you use Arrays.equals, and when checking for equality in test code you use a dedicated assertXyz method (where the exact method depends on the version of JUnit etc).

like image 103
Jon Skeet Avatar answered Nov 20 '25 12:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!