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



我收到一个错误,告诉我没有实现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.
}
}

更改此项:

public class Rate implements Comparable

到此:

public class Rate implements Comparable<Rate>

请确保覆盖equals和hashCode,并且当两个Rates相同时,equals方法给出的行为与compareTo相同。如果你不这样做,你会经历微妙的、违反直觉的错误。

最新更新