sozhen
sozhen

Reputation: 7677

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!

Upvotes: 0

Views: 157

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533492

Your MyComparator<Employee> is the same as writing MyComparator<E extends Object>

What I expect you meant to write was

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

In this case Employee is a class instead of a parameterized type.

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213223

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

Upvotes: 4

Related Questions