开发者

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?


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 ArrayList();
List list2 = list1;

list1.equals(list2); // returns true;

If you want "deep equals", instantiate anything that extends AbstractList, such as ArrayList.

List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();

list1.add("hello");
list2.add("hello");
System.out.println(list1.equals(list2)); // will print true

list1.add("foo");
list2.add("bar");
System.out.println(list1.equals(list2)); // will print false


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜