javaguy javaguy - 5 months ago 26
Java Question

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?

Answer

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.