The code below is for the ArrayList of String. I want to know what's the complexity of the Collections.frequency() function.
List 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).