What is the Complexity of the Java's in-built function Collections.frequency(list, element)?

不打扰是莪最后的温柔 提交于 2020-01-25 00:59:19

问题


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"));

回答1:


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

So it's O(n).



来源:https://stackoverflow.com/questions/48734589/what-is-the-complexity-of-the-javas-in-built-function-collections-frequencylis

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