What is the cost of ContainsAll in Java?

前端 未结 4 1725
南旧
南旧 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)
    0 讨论(0)
  • 2021-01-15 04:01

    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

    0 讨论(0)
  • 2021-01-15 04:11
    • first, it iterates each element of the supplied collection
    • then it iterates all elements of the list and compares the current element with them using .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;
    }
    
    0 讨论(0)
  • 2021-01-15 04:17

    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

    0 讨论(0)
提交回复
热议问题