This question already has answers here:
Very confused by Java 8 Comparator type inference
                                
                                    (4个答案)
                                
                        
                在8个月前关闭。
            
        

我已经列出了成对的。我想首先根据键对它们进行排序,如果键相同,则根据值进行排序。

我尝试了以下代码,但引发了不兼容类型的异常:无法推断类型变量T

 List<Pair<Integer,Integer>> list = new ArrayList<>();
 list.sort(Comparator.comparingInt(Pair::getKey).thenComparingInt(Pair::getValue);


错误:


  不兼容的类型:无法推断类型变量T
                                                                                       (参数不匹配;方法参考无效
        类Pair中的getKey方法不能应用于给定类型
          必需:无参数
          找到:对象
          原因:实际参数和正式参数列表的长度不同)
  
  其中T,K,V是类型变量:
      T扩展了在方法compareInt(ToIntFunction)中声明的Object
      K扩展在类Pair中声明的对象
      V扩展在Pair类中声明的Object

最佳答案

您需要帮助编译器为比较器推断适当的类型:

list.sort(Comparator.<Pair<Integer, Integer>>comparingInt(Pair::getKey).thenComparingInt(Pair::getValue));

关于java - 对对列表进行排序java ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57624889/

10-11 13:15
查看更多