Kim12
Kim12

Reputation: 23

Why am I getting this error about the compareTo method?

I am trying to understand the compareTo method. I wrote this class AboutcompareTo, but i am stuck in why/how i get this error?- the code is nearly finished. anyone can explain in details what i am doing wrong. Thanks

the code:

public class AboutCompareTo {

    public static void main(String[] args) {
        Fruit[] fruits = { new Fruit(2), new Fruit(3), new Fruit(1) };
        java.util.Arrays.sort(fruits);
    }

}

class Fruit implements Comparable<Fruit> {
    private double weight;

    public Fruit(double weight) {
        this.weight = weight;
    }

    @Override
    public int compareTo(Fruit o) {
        Fruit f = (Fruit) o;
        if (Fruit > o.Fruit)  // <-- the error
            return 1;
        else if ((Fruit < o.Fruit))  // <-- the error
            return -1;
        else
            return 0;

    }

} 

Upvotes: 0

Views: 3766

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

The compareTo method compares an instance of your class, i.e. this Fruit, to an instance of another Fruit passed to you as a parameter. Therefore, the comparison needs to be between o's weight, and your own weight:

@Override
public int compareTo(Fruit o) {
    if (this.weight > o.weight)
        return 1;
    else if (this.weight < o.weight)
        return -1;
    else
        return 0;
}

Note 1: I used this.weight to refer to the weight of this Fruit. I did this to point out that weight attribute belongs to this instance; however, you can omit this. from the expression, i.e. use weight > o.weight instead.

Note 2: I assume that you did this for a learning exercise. For production code Java class library provides a pre-built method for comparing doubles - i.e. Double.compare. You can rewrite the method in a single line:

@Override
public int compareTo(Fruit o) {
    return Double.compare(weight, o.weight);
}

Upvotes: 5

Related Questions