What is an easy way to compare ArrayLists for equality using JUnit? Do I need to implement the equality interface? Or is there a simple JUnit method that makes it easier?
-
Possible duplicate of [Assert List in Junit](http://stackoverflow.com/questions/3236880/assert-list-in-junit) – djeikyb Nov 16 '16 at 21:44
3 Answers
You need to do nothing special for list equality, just use assertEquals.
ArrayList and other lists implement equals() by checking that all objects in the corresponding positions of the lists are equal, using the equals() method of the objects. So you might want to check that the objects in the list implement equals correctly.

- 55,348
- 14
- 97
- 151
-
The problem with this answer is that it won't report the contents of the list on failure. Try using assertThat(a, is(b)); instead. starblue's warning about implementing equals still holds. See also [duplicate question 3236880](http://stackoverflow.com/questions/3236880/assert-list-in-junit): better answers and code samples there. – Barett Jun 04 '13 at 23:30
-
Update from the future: this doesn't seem to work on arrays of primitive types, and in either case, assertEquals(Object[], Object[]) is deprecated. Use assertArrayEquals. – johncip May 04 '14 at 05:13
-
@johncip That's good advice for arrays, but the question was about `ArrayList`. – starblue May 04 '14 at 19:24
-
Oops! I was looking at some array equality questions and this got mixed in somehow. Should have read more carefully. In that case you're right about arrayEquals, obviously. – johncip May 04 '14 at 22:18
You might want to check the documentation for List.equals
.

- 145,806
- 30
- 211
- 305
-
So does this mean that if I have a List
I will need to override equals for SomeClass ? – Alex Baranosky Oct 03 '09 at 03:21 -
6It will compare the elements of the lists with `Object.equals`. By default this will be true if they are the same instance. If you want to allows different objects with the same internal data to match, then they should provide `SomeClass` with an `equals` (and `hashCode`) method. – Tom Hawtin - tackline Oct 03 '09 at 03:37
I think this might be a slightly too easy answer (although it is correct). Testing ArrayLists for equals implies you have given thought to equality of the elements. If the elements are Integers that is all fine. But if they are instances of your own domain classes, then you should be made aware of the pitfalls surrounding equality (and cloning). Please check out:
http://www.artima.com/lejava/articles/equality.html
for a good set of tips about implementing equality. On an aside: If you ever need to clone objects, consider the use of copy constructors instead of implementing cloneable. Cloneable introduces a whole set of problems you might not expect.

- 15,870
- 5
- 45
- 60