6

编译下面的代码时,出现以下错误:

PersonalInformation 不是抽象的,不会覆盖 Comparable 中的抽象方法 compareTo(Object)

我认为这意味着我的compareTo方法有问题。但一切似乎都很好。有人有建议吗?

import java.util.*;
public class PersonalInformation implements Comparable
{
private String givenName;
private String middleInitial;
private String surname;
private String gender;
private String emailAddress;
private String nationalId;
private String telephoneNum;
private String birthday;

public PersonalInformation(String gN, String mI, 
        String sur, String gen, String eMa, String natId,
        String teleNum, String birthd)

{
        givenName = gN;
        middleInitial = mI;
        surname = sur;
        gender = gen;
        emailAddress = eMa;
        nationalId = natId;
        telephoneNum = teleNum;
        birthday = birthd;


}


public int compareTo(PersonalInformation pi)
{
 return (this.gender).compareTo(pi.gender);
}

}
4

3 回答 3

20

做这个:

public int compareTo(Object pi) {
    return ((PersonalInformation )(this.gender)).compareTo(((PersonalInformation ) pi).gender);
}

或更好

public class PersonalInformation implements Comparable<PersonalInformation>

如果您实现Comparable接口,则必须使用第一种方法为所有对象实现它,或者以第二种方式键入您的类。

于 2012-02-20T14:23:58.380 回答
6

请参阅 juergen d 的答案,好多了。

您正在重载该方法:

public int compareTo(PersonalInformation pi)
{
    return (this.gender).compareTo(pi.gender);
}

而不是覆盖它:

public int compareTo(Object pi)

它可能是这样的:

public int compareTo(Object pi)
{
    if ( ! pi instanceof PersonalInformation )
        return false;
    return (this.gender).compareTo( (PersonalInformation)pi.gender );
}
于 2012-02-20T14:23:40.483 回答
6

您需要实现Comparable<PersonalInformation>而不是Comparable让您的类编译和工作。

If you are implementing Comparable, the expected method signature is compareTo(Object o) which is missing in your class and hence the error.

于 2012-02-20T14:25:14.527 回答