I posted a bunch of stuff in comments I think it warrants its own answer.
As everyone says here, using equals() depends on the order. If you don't care about order, you have 3 options.
Option 1
Use containsAll()
. This option is not ideal, in my opinion, because it offers worst case performance, O(n^2).
Option 2
There are two variations to this:
2a) If you don't care about maintaining the order ofyour lists... use Collections.sort()
on both list. Then use the equals()
. This is O(nlogn), because you do two sorts, and then an O(n) comparison.
2b) If you need to maintain the lists' order, you can copy both lists first. THEN you can use solution 2a on both the copied lists. However this might be unattractive if copying is very expensive.
This leads to:
Option 3
If your requirements are the same as part 2b, but copying is too expensive. You can use a TreeSet to do the sorting for you. Dump each list into its own TreeSet. It will be sorted in the set, and the original lists will remain intact. Then perform an equals()
comparison on both TreeSet
s. The TreeSets
s can be built in O(nlogn) time, and the equals()
is O(n).
Take your pick :-).
EDIT: I almost forgot the same caveat that Laurence Gonsalves points out. The TreeSet implementation will eliminate duplicates. If you care about duplicates, you will need some sort of sorted multiset.