What is the cost of ContainsAll in Java?

前端 未结 4 1733
南旧
南旧 2021-01-15 03:15

I discovered containsAll() (a List interface method) during some coding today, and it looks pretty slick. Does anyone know how much this costs in

4条回答
  •  失恋的感觉
    2021-01-15 03:52

    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:

    • For a HashSet/HashMap this might be O(1) (best case, no collisions), so the overall runtime of containsAll would still be O(n)
    • For an 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)

提交回复
热议问题