Java内置函数Collections.frequency(list,element)的复杂性是什么? [英] What is the Complexity of the Java's in-built function Collections.frequency(list, element)?

查看:94
本文介绍了Java内置函数Collections.frequency(list,element)的复杂性是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码用于String的ArrayList。我想知道 Collections.frequency()函数的复杂性。

The code below is for the ArrayList of String. I want to know what's the complexity of the Collections.frequency() function.

List<String> list = new ArrayList<>();
list.add("sample");
list.add("sample1");
list.add("sample");
list.add("sample");
list.add("sample");
list.add("sample");
System.out.println("sample is repeated : " + Collections.frequency(list, "sample"));


推荐答案

Collections.frequency 具有以下实现(在Java 9中):

Collections.frequency has the following implementation (in Java 9):

public static int frequency(Collection<?> c, Object o) {
    int result = 0;
    if (o == null) {
        for (Object e : c)
            if (e == null)
                result++;
    } else {
        for (Object e : c)
            if (o.equals(e))
                result++;
    }
    return result;
}

因此它是 O(n)

这篇关于Java内置函数Collections.frequency(list,element)的复杂性是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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