views:

102

answers:

3
+2  Q: 

Compare two lists.

I want to compare two lists. Since we code to interface using List, which does not inherit the equals from from the Object class. How do I do this?

+1  A: 

You can still use equals. All objects implement it, and your lists are still objects and override equals as you need it.

tangens
+7  A: 

Even though the List interface does not contain an equals method, the list-classes may (and does) still implement the equals method.

From the API docs on AbstractList (inherited by for instance ArrayList, LinkedList, Vector):

public boolean equals(Object o)

Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.

The same applies to for instance the toString, hashCode method and so on.


As @Pascal mentions in the comments, the List interface mentions the equals method and states the following in the documentation:

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods.

aioobe
Good point. But I'm not sure what you mean exactly. All objects implement an `equals` method, so I would say the opposite holds: I wouldn't be able to *not* implement the equals method. Made it a community wiki, so please edit and improve the answer if you like.
aioobe
I realize I wasn't clear and you are correct (and so does the answer now).
Pascal Thivent
+1  A: 

It's the usual story: you have to consider "shallow equals" and "deep equals".

The default behavior that you get out of java.lang.Object is "shallow equals". It'll check to see if list1 and list2 are the same references:

List list1 = new List();
List list2 = list1;
list1.equals(list2); // returns true;

If you want "deep equals", where you check equality element by element, you'll have to write your own method to do it.

duffymo