How does Java quickly compare two collection are exactly the same in java?
for example:
if this collection is Set, compare their contain the same object and their size are same.
Code looks like the following
public boolean isSameSets(Set<T> set1, Set<T> set2){
if (set1.size() != set2.size()) {
return false;
}
return set1.containAll(set2) && set2.containAll(set1);
}
But if the collection is list, because list is sorted collection, we can iterate to compare every element, I think this way is not the best, who could please tell me how to quickly compare them?
========================================================
Thanks everyone, actually, Collection equals method can do it, include Set and List.
The Collection
equals(Object)method should do this for you. The javadoc explains exactly what “equals” means for a Collection, and the semantics are further refined for the interfaces that extend Collection.Different collection classes will have their own implementations of this method, tuned for their respective semantic models and representations. So for instance, the
equalsmethod on aListwould take account of the element order, but theequalsmethod on aSetwould typically not.Someone asks:
In general, no. For instance, two lists that have the same elements are not necessarily equal. You have to also consider list order. (And besides, using
containsAllto compare lists isO(N^2)where an efficientequalsimplementation for aListshould beO(N)… in the worst case.)The same applies to using
retainsAll.