Java中的ContainsAll的成本是多少? [英] What is the cost of ContainsAll in Java?

查看:189
本文介绍了Java中的ContainsAll的成本是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天在一些编码中发现了containsAll()(一种List接口方法),它看起来很漂亮.有谁知道在性能/迭代方面要花多少钱?

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.

推荐答案

  • 首先,迭代提供的集合中的每个元素
  • 然后迭代列表的所有元素,并使用.equals(..)将当前元素与它们进行比较(注意:正如您在问题中所指定的,这是关于列表的.其他集合的行为有所不同)
    • 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)
    • 所以它是O(n * m),其中n和m是两个集合的大小.

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

      这篇关于Java中的ContainsAll的成本是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆