我有以下类来实现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));
}
}
Run Code Online (Sandbox Code Playgroud)
错误消息:
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)
Run Code Online (Sandbox Code Playgroud)
我非常积极,我不必Object在compareTo() 方法中转换为root类.那么我可以做错什么呢?
添加泛型类型以匹配compareTo方法
public class Person implements Comparable<Person> {
Run Code Online (Sandbox Code Playgroud)
如果您要使用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));
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不使用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));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1803 次 |
| 最近记录: |