0

我有以下实现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)

我很肯定我不必Object在该compareTo() 方法中强制转换为根类。那么我做错了什么?

4

4 回答 4

6

添加泛型类型以匹配compareTo方法

public class Person implements Comparable<Person> { 
于 2013-10-16T13:17:56.747 回答
6

如果你要使用 Generic 那么你的类看起来像这样

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));
     }      
}

如果你没有使用 Generic 那么你的类看起来像

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));
     }  
}
于 2013-10-16T13:19:10.270 回答
1
public int compareTo(Object o) {
        Person newObject =(Person)o;
        int thisCmp = age.compareTo(newObject.age);        
        return (thisCmp != 0 ? thisCmp : lName.compareTo(newObject.Name));
    }
于 2013-10-16T13:23:25.750 回答
1

问题是,当您实现时Comparable,暗示您要比较的类型是Object. 所以,Comparable是一样的Comparable<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));
 }
于 2013-10-16T13:26:05.973 回答