2014-10-27 171 views
0

我收到一個錯誤,告訴我我沒有在執行compareTo方法時執行此操作。我的代碼看起來像這樣(我省略了存取方法,因爲它們是很好的):速率並不抽象,也不會覆蓋java.lang.Comparable中的抽象方法compareTo(java.lang.Object)

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. 

} 
} 

回答

3

更改此:

public class Rate implements Comparable 

這樣:

public class Rate implements Comparable<Rate> 

確保你重寫equals和hashCode,並且當兩個速率相同時,您的equals方法會給出與compareTo相同的行爲。如果你不這樣做,你會遇到微妙的,違反直覺的錯誤。

+0

它總是小事情。謝謝你,現在它工作得很好! – 2014-10-27 14:14:55

+0

如果我幫你,請回答並接受它。 – duffymo 2014-10-27 14:20:02

相關問題