2013-10-16 35 views
0

我實現了compareTo()方法我有以下類實現了Comparable接口。我已經在其中定義了compareTo()方法,但不知何故編譯器仍然告訴我必須實現它。編譯器告訴我,當我已經有

public class Person implements Comparable { 
    private String fName; 
    private String lName; 
    private Integer age; 
    public Person (String fName, String lName, int age) 
    { 
     this.fName = fName; 
     this.lName = lName; 
     this.age = age; 
    } 

    // Compare ages, if ages match then compare last names 
    public int compareTo(Person o) { 
     int thisCmp = age.compareTo(o.age);   
     return (thisCmp != 0 ? thisCmp : lName.compareTo(o.Name)); 
    } 
} 

錯誤消息:

The type Person must implement the inherited abstract method Comparable.compareTo(Object) 
Syntax error on token "=", delete this token 
    at me.myname.mypkg.Person.<init>(Person.java:6) 

我敢肯定的,我沒有投給根類ObjectcompareTo()方法。那麼,我可能做錯了什麼?

回答

6

如果你要去,如果你不使用泛型,然後你的類看起來像使用泛型,那麼你的類這個樣子的

class Person implements Comparable<Person> { 

    private String fName; 
    private String lName; 
    private Integer age; 

    public int compareTo(Person o) { 
     int thisCmp = age.compareTo(o.age);   
     return (thisCmp != 0 ? thisCmp : lName.compareTo(o.fName)); 
    }  
} 

class Person implements Comparable { 

    private String fName; 
    private String lName; 
    private Integer age;  
    public int compareTo(Object obj) { 
     Person o= (Person) obj; 
     int thisCmp = age.compareTo(o.age);   
     return (thisCmp != 0 ? thisCmp : lName.compareTo(o.fName)); 
    } 
} 
6

添加泛型類型相匹配的compareTo方法

public class Person implements Comparable<Person> { 
+0

非常感謝。我可以問,如果我將內部變量聲明爲一個變量,那麼是否有可能擁有自己的compareTo()方法? – kype

+0

這會使執行過程變得複雜...... – Reimeus

+0

好的,謝謝你,會按照原文 – kype

1
public int compareTo(Object o) { 
     Person newObject =(Person)o; 
     int thisCmp = age.compareTo(newObject.age);   
     return (thisCmp != 0 ? thisCmp : lName.compareTo(newObject.Name)); 
    } 
1

問題是,當你執行Comparable時,暗示你正在比較的類型是Object。所以,ComparableComparable<Object>相同。你有兩種選擇之一。

方案一(由Reimeus陳述,也是最好的選擇):添加參數,以此來聲明:

public class Person implements Comparable<Person> { 

選擇二:修改方法調用(不太優雅的解決方案):

// Compare ages, if ages match then compare last names 
public int compareTo(Object o) { 
    Person p = (Person)o; 
    int thisCmp = age.compareTo(p.age);   
    return (thisCmp != 0 ? thisCmp : lName.compareTo(p.Name)); 
} 
相關問題