Comparator with double type

前端 未结 10 1581
盖世英雄少女心
盖世英雄少女心 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条回答
  •  旧时难觅i
    2020-11-28 12:09

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

    • Less than zero, if the first value is less than the second;
    • Equal to zero, if the two values are equal;
    • Greater than zero, if the first value is greater than the second;

    You don't need to return a double. You must return an int to implement the Comparator interface. You just have to return the correct int, according to the rules I outlined above.

    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:

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

提交回复
热议问题