Question

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?

Était-ce utile?

La solution

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).

Autres conseils

assertEquals calls the equals object in one of the objects to compare it with the other.

Arrays need to be compared using Arrays.equals() if you want a full comparison of the two arrays, otherwise unfortunately they just use the Object equals method.

See also: equals vs Arrays.equals in Java

Because you create 2 different objects and they point to different locations in the memory. When comparing objects, you use the equals() method inherited from the class Object. Now, if you don't override the method in your class, you will have the default behaviour which is the comparison of objects address. In the code you create 2 arrays, but even though their content is the same, not the content is tested for being equal, but the objects reference by using the inherited equals() method from Object class.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top