【问题标题】:Why Collections.max() method is not support Set<Entry<String,Integer>>为什么 Collections.max() 方法不支持 Set<Entry<String,Integer>>
【发布时间】:2019-03-31 06:22:38
【问题描述】:
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&lt;?extends T&gt;, Comparator&lt;? super T&gt;)”将两个参数作为Set和比较器,效果很好。

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

【问题讨论】:

  • 提供countMap
  • 这两个哪个条目更大? 1:"abc" -&gt; 1000; 2:"CBA" -&gt; 0。你知道吗? Java 没有。 Collections.max 方法采用 Comparable 的集合。集合中的元素必须是 Comparable,或者您需要提供一个 Comparator 来定义如何比较元素。

标签: java collections


【解决方案1】:

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) 

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

Entry 没有实现 Comparable 接口,所以你不能把它传递给这个方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-04
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2012-08-05
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多