I discovered containsAll()
(a List
interface method) during some coding today, and it looks pretty slick. Does anyone know how much this costs in
Use the source, Luke :)
Edit: As Bozho pointed out, you're asking about List.containsAll()
which overrides Collection.containsAll()
. The following ramblings are mainly concerned with the latter:
Most Collection
classes will use the implementation of containsAll from AbstractCollection, which does it like this:
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
There's no guarantee that some implementation does it completely differently, though -- which could result in either better or worse runtime behavior.
The above implementation of containsAll
will be at least O(n) where n is the number of items in the Collection
parameter you pass in, plus whatever time contains
takes:
HashSet
/HashMap
this might be O(1) (best case, no collisions), so the overall runtime of containsAll
would still be O(n)ArrayList
, contains
will take O(m) where m is the number items in the list (not the parameter), so the overall time for containsAll
would be O(n*m)consider
n.ContainsAll(m)
the best possible case scenario is O(m), and that's if n is a perfect hash set.
considering unsorted lists, i can come up with an O(n*log(n) + m*log(m)) algorithm
.equals(..)
(Note: this is about lists, as you specified in the question. Other collections behave differently)So it's O(n*m), where n and m are the sizes of both collections.
public boolean containsAll(Collection<?> c) {
Iterator<?> e = c.iterator();
while (e.hasNext())
if (!contains(e.next()))
return false;
return true;
}
if you are calling A.containsAll(B)
openjdk iterates all elements of B calling A.contains(b).
A.contains(b) iterates all elements of A calling a.equals(b)
This is taken from source for open jdk 7