質問

I have the following class which implements the Comparable interface. I have already defined the compareTo() method in it, but somehow the compiler still tells me I have to implement it.

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 error message:

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)

I'm pretty positive I do not have to cast to root class Object at the compareTo() method. So what can I be doing wrong?

役に立ちましたか?

解決

if you going to use Generic then you class look like this

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

if you are not using Generic then your class look like

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

他のヒント

Add the generic type to match the compareTo method

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

The problem is that when you implement Comparable, it's implied the the type you're comparing is Object. So, Comparable is the same as Comparable<Object>. You have one of two options.

Option one (as stated by Reimeus, and also the best option): Add a parameter to your declaration:

public class Person implements Comparable<Person> {

Option two: Modify your method call (the less elegant solution):

// 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));
 }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top