编译器告诉我在我已经有的时候实现compareTo()方法

时间:2013-10-16 13:16:26

标签: java 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)

我非常积极,我不必在Object方法中转换为根类compareTo()。那么我可以做错什么呢?

4 个答案:

答案 0 :(得分:6)

添加通用类型以匹配compareTo方法

public class Person implements Comparable<Person> { 

答案 1 :(得分: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));
     }  
}

答案 2 :(得分:1)

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

答案 3 :(得分: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));
 }