tags:

views:

392

answers:

3

What is an easy way to compare ArrayLists for equality using JUnit? Do I neeeeeed to implement the equality interface? Or is there a simple JUnit method that makes it easier?

+4  A: 

You might want to check the documentation for List.equals.

Tom Hawtin - tackline
I'm new to Java thanks.
Alex Baranosky
So does this mean that if I have a List<SomeObject> I will need to override equals for SomeClass ?
Alex Baranosky
It 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
+3  A: 

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.

starblue
yep, I noticed when I read the docs.
Alex Baranosky
A: 

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, reconsider implementing cloneable in favor of copy constructors. Cloneable introduces a whole set of problems you might not expect (left as an excercise for the reader for now).

Adriaan Koster