Compare two lists

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

+4
source share
3 answers

Although the List interface does not contain the equals method, list classes can (and still) implement the equals method.

From the API docs to AbstractList (inherited e.g. 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 are the same size, and all the corresponding pairs of elements in two lists are equal.

The same applies, for example, to toString , hashCode , etc.


As @Pascal notes in the comments, the List interface refers to the equals method and points out the following in the documentation:

The List interface sets additional conditions, in addition to those specified in the Collection interface, in iterator contracts, add, remove, equals and hashCode.

+14
source

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

+2
source

This is a common story: you must consider the “shallow equals” and the “deep equals”.

The default behavior that you selected from java.lang.Object is "Shallow Equal." It checks if list1 and list2 are the same links:

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

If you want deep peers, create an instance of everything that extends AbstractList, such as an 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 
0
source

Source: https://habr.com/ru/post/1310630/


All Articles