gpt4 book ai didi

java - 当我已经有时,编译器告诉我实现compareTo()方法

转载 作者:行者123 更新时间:2023-12-01 06:30:55 26 4
gpt4 key购买 nike

我有以下类,它实现了Comparable接口(interface)。我已经在其中定义了 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)

我非常肯定我不必在 compareTo() 方法中转换为根类 Object。那么我可能做错了什么?

最佳答案

如果你要使用 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));
}
}

关于java - 当我已经有时,编译器告诉我实现compareTo()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19404506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com