gpt4 book ai didi

java - 为什么 Collections.max() 方法不支持 Set>

转载 作者:行者123 更新时间:2023-12-01 16:45:17 30 4
gpt4 key购买 nike

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

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

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

最佳答案

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) 

All elements in the collection must implement the Comparable interface.

Entry 未实现 Comparable 接口(interface),因此您无法将其传递给此方法。

T 类型参数约束中的 extends ... Comparable 告诉编译器有关要求。

关于java - 为什么 Collections.max() 方法不支持 Set<Entry<String,Integer>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53009598/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com