这个问题在这里已经有答案了:
泛型类型推断不使用方法链接(2个答案)
四年前关门了。
我需要整理一份要点清单。首先我需要比较x值,然后如果x值相等,就比较y值。所以我想我应该用比较的方法:
Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y);
但我一直得到这样的信息:不兼容的类型:comparator不能转换为comparator。
我还有其他方法可以做这个比较,而且很有效,但我不明白我做错了什么。
2条答案
按热度按时间roqulrg31#
此代码不起作用:
我只是补充了一句
<Point>
之前comparingInt
,它显式声明p
在lambda里。这是必要的,因为由于方法链的原因,java无法推断类型。另请参见泛型类型推断不使用方法链接?
另一种选择是:
在这里,可以毫无问题地推断出类型。但是,您需要使用双重比较,因为
getX
以及getY
返回双精度值。我个人更喜欢这种方法。bbmckpt72#
尝试更改:
到