Unable to override compare () method of comparator

I'm not sure why I got this error below, although I already implemented this method.

"The compare (Student, Student) method of type NameComparator must override or implement the supertype method" in NameComparator.java when implementing the comparison method

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

}
+4
source share
3 answers

Change

public class NameComparator implements Comparator {

to

public class NameComparator implements Comparator<Student> {

When you implement the raw interface Comparator(which is not recommended), your method compareexpects Objectarguments.

+6
source

Comparator<T> - . , Comparator<Object> , , , public int compare(Object s1, Object s2) { .

, Comparator Comparator<Student> .

+3

The method declaration should look like this:

@Override
public int compare(Object s1, Object s2) {

Since you are not adding a generic type to the sentence implements.

Change the class declaration:

public class NameComparator implements Comparator<Student> {

And the error will disappear.

+2
source

All Articles