Comparator with double type

前端 未结 10 1576
盖世英雄少女心
盖世英雄少女心 2020-11-28 11:50

I have written the following code:

public class NewClass2 implements Comparator
{
    public int compare(Point p1, Point p2)
    {
        retur         


        
10条回答
  •  臣服心动
    2020-11-28 12:18

    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.

    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.

提交回复
热议问题