What is the cost of ContainsAll in Java?

强颜欢笑 提交于 2020-01-04 18:21:06

问题


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

The documentation didn't offer much in terms of that.


回答1:


  • 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;
}



回答2:


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)



回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/10199772/what-is-the-cost-of-containsall-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!