gpt4 book ai didi

java - 无法覆盖比较器的compare()方法

转载 作者:行者123 更新时间:2023-12-02 07:50:08 27 4
gpt4 key购买 nike

尽管我已经实现了该方法,但我不确定为什么会出现以下错误。

在实现比较方法时,NameComparator.java 中的“NameComparator 类型的方法compare(Student, Student) 必须重写或实现父类(super class)型方法”

学生.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 + "]";
}

}

NameComparator.java

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

}

最佳答案

改变

public class NameComparator implements Comparator {

public class NameComparator implements Comparator<Student> {

当您实现原始 Comparator 接口(interface)(不建议这样做)时,您的 compare 方法需要 Object 参数。

关于java - 无法覆盖比较器的compare()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28536915/

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