问题
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