双重比较器 [英] Comparator with double type

查看:115
本文介绍了双重比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我已经用stackoverflow帮助写了这个代码:)
但我的getX字段是双重的。我可以解决这个问题吗?
谢谢

Hi I have written this code with the stackoverflow help :) but my "getX" field is double .how can I solve this problem? thanks

代码:

public class NewClass2 implements Comparator<Point>
{
public int compare(Point p1, Point p2)
{
    return (int)(p1.getY() - p2.getY());
}


}

我需要比较()return double not int。即,当3.2 - 3.1 = 0.1时,两个双数3.1和3.2
将被转换为int,差值将为0 !!!!

I need compare() return double not int. i.e., two double number "3.1" and "3.2" when 3.2 - 3.1 = 0.1 which will be cast to int and the difference will be 0!!!!

推荐答案

您不需要返回 double

比较器接口用于为要比较的元素建立排序。使用 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.

您的代码很好。 >

Your code is fine.

对不起,我错了,再次阅读这个问题,这就是你需要的:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆