虽然我已经实现了这个方法,但我不确定为什么会出现以下错误。
“NameComparator类型的方法比较(学生,学生)必须在实现比较方法时在NameComparator.java中覆盖或实现超类型方法
public class Student {
private String name;
private int age;
private String lesson;
private int grade;
public Student() {
}
public Student(String name, int age, String lesson, int grade) {
super();
this.name = name;
this.age = age;
this.lesson = lesson;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getLesson() {
return lesson;
}
public void setLesson(String lesson) {
this.lesson = lesson;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
@Override
public String toString() {
return "[name=" + this.name + ", age=" + this.age + ", lesson="
+ this.lesson + ", grade=" + this.grade + "]";
}
}
import java.util.Comparator;
@SuppressWarnings("rawtypes")
public class NameComparator implements Comparator {
// I’m getting this error for below method "The method compare(Student, Student) of type NameComparator must override or implement a super type method"
@Override
public int compare(Student s1, Student s2) {
String name1 = o1.getName();
String name2 = o2.getName();
// ascending order (descending order would be: name2.compareTo(name1))
return name1.compareTo(name2);
}
}
答案 0 :(得分:7)
更改
public class NameComparator implements Comparator {
到
public class NameComparator implements Comparator<Student> {
当您实现原始Comparator
接口(不建议使用)时,您的compare
方法需要Object
个参数。
答案 1 :(得分:3)
Comparator<T>
接口是通用接口。因此,它采用了Comparator<Object>
的默认实现,这意味着它需要实现public int compare(Object s1, Object s2) {
。
要解决此问题,只需在您的课程声明中将Comparator
替换为Comparator<Student>
。
答案 2 :(得分:2)
方法声明必须如下:
@Override
public int compare(Object s1, Object s2) {
因为您没有在implements
子句中添加泛型类型。
将班级声明更改为:
public class NameComparator implements Comparator<Student> {
错误将消失。