Search code examples
javagenericscomparatorcomparable

Cannot call instance method in a Comparator generic class


My question is close to this one (Static method in a generic class?) but a bit different I think?

Say I have a Employee class with an instance method getSalary()

public class Employee {
    protected long employeeId;
    protected int salary;

    public int getSalary() {
        return salary;
    }
}

And also a Comparator generic class MyComparator

public class MyComparator<Employee> implements Comparator<Employee> {
    public int compare(Employee emp1, Employee emp2) {
        return emp1.getSalary() - emp2.getSalary();
    }
}

Now I have a warning of MyComparator<Employee> and error of calling the getSalary() instance method.

I think I am missing something here but not exact understand what is going on? What is the best way to declare a generic comparator over Employee class? The best practice? Or implementing a Comparable of Employee in below code is suggested?

public class Employee implements Comparable<Employee> {
    protected long employeeId;
    protected int salary;

    public int getSalary() {
        return salary;
    }

    @Override
    public int compareTo(Employee e) {
        return this.salary - e.salary;
    }
}

Any suggestions welcome and appreciated!


Solution

  • You are declaring a type parameter Employee in your Comparator class. That class declaration is same as:

    public class MyComparator<T> implements Comparator<T>
    

    Get the issue? You should change that class to:

    public class MyComparator implements Comparator<Employee> {
        public int compare(Employee emp1, Employee emp2) {
            return emp1.getSalary() - emp2.getSalary();
        }
    }