为什么Collections.max()方法不支持Set <Entry <String,Integer >>

bla*_*ack 0 java collections

String key = Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();
System.out.println(key);
Set<Entry<String,Integer>> entrySet = countMap.entrySet();
Collections.max(countMap.entrySet());
Run Code Online (Sandbox Code Playgroud)

这里第一行代码" Collections.max(Collection<?extends T>, Comparator<? super T>)"将两个参数作为Set和比较器,工作正常.

但是最后一行代码" Collections.max(countMap.entrySet());"给出了编译时错误,说" 类型集合中的方法max(Collection)不适用于参数(Set>) ".需要对上述代码进行解释.

Pet*_*ham 5

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max(java.util.Collection)

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) 
Run Code Online (Sandbox Code Playgroud)

集合中的所有元素都必须实现Comparable接口.

Entry 没有实现Comparable接口,因此您无法将其传递给此方法.

类型参数的约束中的extends... 是告诉编译器有关需求的内容.ComparableT