Search code examples
javasortingcomparablecompareto

How to override compareTo method for doubles?


I'm currently having some trouble understanding how the compareTo method works for the Comparable class, and how to override it. I have array of pairs, each of which hold 2 double values, that I'm trying to sort. This is what I tried:

static class Pair implements Comparable<Pair>
{
    double x;
    double y;
    Pair(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
    public double compareTo(Pair other)
    {
        return y - other.y;
    }
}

However, it doesn't compile and instead gives me this error:

Main.java:5: error: Pair is not abstract and does not override abstract method compareTo(Pair) in Comparable
    static class Pair implements Comparable<Pair>
           ^
Main.java:14: error: compareTo(Pair) in Pair cannot implement compareTo(T) in Comparable
        public double compareTo(Pair other)
                      ^
  return type double is not compatible with int
  where T is a type-variable:
    T extends Object declared in interface Comparable
2 errors

It worked when it was with integers, but not with doubles, why is that? And how could I make it work with doubles? Thanks.


Solution

  • For example:

       static class Pair implements Comparable<Pair> {
    
            double x;
            double y;
    
            Pair(double x, double y) {
                this.x = x;
                this.y = y;
            }
    
            public int compareTo(Pair other) {
                if (y > other.y) {
                    return 1;
                } else if(y<other.y)  {
                    return -1;
                } else {
                    return 0;
                }
            }
        }
    

    or (better variant):

        static class Pair implements Comparable<Pair> {
    
            double x;
            double y;
    
            Pair(double x, double y) {
                this.x = x;
                this.y = y;
            }
    
            public int compareTo(Pair other) {
                return Double.compare(this.y, other.y);
            }
        }