简体   繁体   中英

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

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 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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM