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?
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).
See more on this question at Stackoverflow