I’m not sure why I get this below error though I already implemented the method.
“The method compare(Student, Student) of type NameComparator must override or implement a supertype method” in NameComparator.java while implementing the compare method
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);
}
}
Change
public class NameComparator implements Comparator {
to
public class NameComparator implements Comparator<Student> {
When you implement the raw Comparator
interface (which is not advised), your compare
method expects Object
arguments.
The Comparator<T>
interface is a generic interface. As is, it took the default implementation of Comparator<Object>
, which would mean that it is expecting public int compare(Object s1, Object s2) {
to be implemented.
To fix this, simply replace Comparator
with Comparator<Student>
in you class decleration.
The method declaration must looks like:
@Override
public int compare(Object s1, Object s2) {
Because you ot add the generic type at the implements
clause.
Change the class declaration to:
public class NameComparator implements Comparator<Student> {
And the error will gone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With