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?
views:
102answers:
3You can still use equals
. All objects implement it, and your lists are still objects and override equals
as you need it.
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.
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.