Comparator with double type

user472221 picture user472221 · Nov 22, 2010 · Viewed 83.7k times · Source

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.

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?

Answer

Peter Lawrey picture Peter Lawrey · Nov 22, 2010

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.