java – 比较器比较

参见英文答案 > Generic type inference not working with method chaining?1个
我需要对点列表进行排序.首先,我需要比较x值,然后如果x值相等,则y值.所以我以为我会使用thenComparing方法
Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y);

但我一直收到消息:不兼容的类型:比较器<对象>无法转换为比较器< Point>.

还有其他方法我可以进行这种比较,它有效,但我不明白我在这里做错了什么.

解决方法

这段代码确实有效:
Comparator<Point> cmp = Comparator.<Point> comparingInt(p -> p.x)
                                  .thenComparingInt(p -> p.y);

我只添加了< Point>在comparisonInt之前,它明确地声明了lambda中p的类型.这是必要的,因为Java不能推断类型,因为方法链.

另见Generic type inference not working with method chaining?

这是另一种选择:

Comparator<Point> cmp = Comparator.comparingDouble(Point::getX)
                                  .thenComparingDouble(Point::getY);

这里,可以毫无问题地推断出类型.但是,您需要使用双重比较,因为getX和getY返回double值.我个人更喜欢这种方法.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...