Java 双型比较器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4242023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:56:00  来源:igfitidea点击:

Comparator with double type

javacastingdoublecomparator

提问by user472221

I have written the following code:

我编写了以下代码:

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

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.

如果我假设有两个双数,3.2 - 3.1,差异应该是0.1。但是,当我将数字转换为 int 时,差异最终为0,这是不正确的。

I therefore need compare()to return a double, not an int. The problem is, my getXfield is a double. How can I solve this problem?

因此compare(),我需要返回一个 double,而不是一个 int。问题是,我的getX领域是双重的。我怎么解决这个问题?

采纳答案by dteoh

You don't need to return double.

你不需要返回double

The Comparatorinterface is used to establish an ordering for the elements being compared. Having fields that use doubleis irrelevant to this ordering.

Comparator接口用于为被比较的元素建立排序。使用的字段double与此排序无关。

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;
    }    
}

回答by R. Martinho Fernandes

The method compareshould return an int. It is a number that is either:

该方法compare应该返回一个int. 它是一个数字,可以是:

  • Lessthan zero, if the first value is lessthan the second;
  • Equalto zero, if the two values are equal;
  • Greaterthan zero, if the first value is greaterthan the second;
  • 小于零,如果第一个值小于第二个;
  • 等于零,如果这两个值相等;
  • 更大的大于零,如果第一个值是大于比第二;

You don't needto return a double. You mustreturn an intto implement the Comparatorinterface. You just have to return the correct int, according to the rules I outlined above.

无需返回double. 您必须返回 anint才能实现该Comparator接口。您只需要int根据我上面概述的规则返回正确的。

You can't simply cast from int, as, like you said, a difference of 0.1 will result in 0. You can simply do this:

你不能简单地从 int 转换,就像你说的,0.1 的差异将导致 0。你可以简单地这样做:

public int compare(Point p1, Point p2)
{
    double delta= p1.getY() - p2.getY();
    if(delta > 0) return 1;
    if(delta < 0) return -1;
    return 0;
}

But since comparison of floating-point values is always troublesome, you should compare within a certain range (see this question), something like this:

但是由于浮点值的比较总是很麻烦,您应该在一定范围内进行比较(请参阅此问题),如下所示:

public int compare(Point p1, Point p2)
{
    double delta = p1.getY() - p2.getY();
    if(delta > 0.00001) return 1;
    if(delta < -0.00001) return -1;
    return 0;
}

回答by Peter Lawrey

I suggest you use the builtin method Double.compare(). If you need a range for double values to be equal you can use chcek for that first.

我建议您使用内置方法 Double.compare()。如果您需要双精度值的范围相等,您可以先使用 chcek。

return Double.compare(p1.getY(), p2.gety());

or

或者

if(Math.abs(p1.getY()-p2.getY()) < ERR) return 0;    
return Double.compare(p1.getY(), p2.gety());

The problem with using < and > is that NaN will return false in both cases resulting in a possibly inconsistent handling. e.g. NaN is defined as not being equal to anything, even itself however in @suihock's and @Martinho's solutions, if either value is NaN the method will return 0 everytime, implying that NaN is equal to everything.

使用 < 和 > 的问题是 NaN 在这两种情况下都将返回 false,从而导致处理可能不一致。例如,NaN 被定义为不等于任何东西,即使是它本身,但在@suihock 和@Martinho 的解决方案中,如果其中一个值为 NaN,则该方法每次都将返回 0,这意味着 NaN 等于一切。

回答by HasnainMamdani

Well, you could multiply those double values by an appropriate factor before converting into integer, for eg. in your case since its only one decimal place so 10 would be a good factor;

好吧,您可以在转换为整数之前将这些双精度值乘以适当的因子,例如。在您的情况下,因为它只有一位小数,所以 10 将是一个很好的因素;

return (int)(p1.getY()*10 - p2.getY()*10);

回答by Miguel Durazo

I just want to expand on Peter Lawrey answer on JDK 8, if you do it like this:

我只想扩展 Peter Lawrey 在 JDK 8 上的回答,如果你这样做的话:

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

You could define this comparator using a lambda expression pretty easily

你可以很容易地使用 lambda 表达式定义这个比较器

(Point p1,Point p2) -> Double.compare(p1.getY(), p2.gety())  

Better yet, you could use a member reference like this:

更好的是,您可以使用这样的成员引用:

Double::compare

回答by Jan Dolejsi

Since Java 1.8 you can also use

从 Java 1.8 开始,您还可以使用

Comparator.comparingDouble(p -> p.getY())

回答by Ready Android

Use Double.compare(/**double value 1*/, /**double value 2*/);with a new Comparator for your model class double value.

Double.compare(/**double value 1*/, /**double value 2*/);与模型类双值的新 Comparator 一起使用。

public static List<MyModel> sortByDouble(List<MyModel> modelList) {
        Collections.sort(modelList, new Comparator<MyModel>() {
            @Override
            public int compare(MyModels1, MyModels2) {
                double s1Distance = Double.parseDouble(!TextUtils.isEmpty(s1.distance) ? s1.distance : "0");
                double s2Distance = Double.parseDouble(!TextUtils.isEmpty(s2.distance) ? s2.distance : "0");
                return Double.compare(s1Distance, s2Distance);
            }
        });
        return modelList;
    }

回答by Stan Sokolov

Double min  = Arrays.stream(myArray).min(Double::compare).get();

回答by QM.py

It is so convinent in Java 8, choose anyone just as you wish:

它在 Java 8 中非常方便,您可以随意选择任何人:

Comparator<someClass> cp = (a, b) ->  Double.compare(a.getScore(), b.getScore());

Comparator<someClass> cp = Comparator.comparing(someClass::getScore);

Comparator<someClass> cp = Comparator.comparingDouble(someClass::getScore);

回答by cringineer

int compare(Double first, Double second) {
    if (Math.abs(first - second) < 1E-6) {
        return 0;
    } else {
        return Double.compare(first, second);
    }
}