Rate不是抽象的,并且不会覆盖java.lang.Comparable中的抽象方法compareTo(java.lang.Object)

时间:2014-10-27 14:05:46

标签: interface comparable

我收到错误告诉我,我没有实现compareTo方法。我的代码看起来像这样(我省略了访问器方法,因为它们很好):

public class Rate implements Comparable
{ 
private int month;
private int day;
private int year;
private double rate;
private int a;  
private int b;
private int c;
private int d;

// The constructor method for the class
public Rate(int month0, int day0, int year0, double rate0)
{
    month = month0;
    day = day0;
    year = year0;
    rate = rate0;
}
public int compareTo(Rate obj) // @param obj the Rate object that will be compared another Rate object.
{
    a = (int)rate - (int)obj.getRate();
    b = year - obj.getYear();
    c = month - obj.getMonth();
    d = day - obj.getDay();

    if (a != 0)
        return a; // @return a The difference between rates for the two objects
    else if (b != 0)
        return b; // @return b The difference between years for the two objects
    else if (c != 0)
        return c; // @return c The difference between month for the two objects
    else if (d != 0)
        return d; // @return d The difference between days for the two objects
    else
        return 0; // @return 0 if the two objects are totally equal.

}
}

1 个答案:

答案 0 :(得分:3)

改变这个:

public class Rate implements Comparable

到此:

public class Rate implements Comparable<Rate>

确保覆盖equals和hashCode,并且当两个Rate相同时,equals方法提供与compareTo相同的行为。如果不这样做,你会遇到微妙的,违反直觉的错误。