What is the simplest way to find if two Lists contain exactly the same elements, in the standard Java libraries?
It shouldn’t matter if the two Lists are the same instance or not, and it shouldn’t matter if the type parameter of the Lists are different.
e.g.
List list1
List<String> list2;
// ... construct etc
list1.add("A");
list2.add("A");
// the function, given these two lists, should return true
There’s probably something staring me in the face I know 🙂
EDIT: To clarify, I was looking for the EXACT same elements and number of elements, in order.
If you care about order, then just use the equals method:
From the javadoc:
If you want to check independent of order, you could copy all of the elements to Sets and use equals on the resulting Sets:
A limitation of this approach is that it not only ignores order, but also frequency of duplicate elements. For example, if
list1was ["A", "B", "A"] andlist2was ["A", "B", "B"] theSetapproach would consider them to be equal.If you need to be insensitive to order but sensitive to the frequency of duplicates you can either: