双型比较器 [英] Comparator with double type
问题描述
我编写了以下代码:
public class NewClass2 implements Comparator<Point>
{
public int compare(Point p1, Point p2)
{
return (int)(p1.getY() - p2.getY());
}
}
如果我假设有两个双数,3.2 - 3.1
,差异应该是 0.1
.然而,当我将数字转换为 int 时,差异最终为 0
,这是不正确的.
If I let's say have two double numbers, 3.2 - 3.1
, the difference should be 0.1
. When I cast the number to an int, however, the difference ends up as 0
, which is not correct.
因此我需要 compare()
返回双精度值,而不是整数.问题是,我的 getX
字段是双精度的.我该如何解决这个问题?
I therefore need compare()
to return a double, not an int. The problem is, my getX
field is a double. How can I solve this problem?
推荐答案
不需要返回double
.
Comparator
接口用于为被比较的元素建立排序.使用 double
的字段与此顺序无关.
The Comparator
interface is used to establish an ordering for the elements being compared. Having fields that use double
is irrelevant to this ordering.
你的代码没问题.
抱歉,我错了,再次阅读问题,这就是您所需要的:
Sorry, I was wrong, reading the question again, this is what you need:
public class NewClass2 implements Comparator<Point> {
public int compare(Point p1, Point p2) {
if (p1.getY() < p2.getY()) return -1;
if (p1.getY() > p2.getY()) return 1;
return 0;
}
}
这篇关于双型比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!