0

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!

Community
  • 1
  • 1
sozhen
  • 7,627
  • 14
  • 36
  • 53
  • 1
    "Now I have a warning of MyComparator and error of calling the getSalary() instance method." What warning? What error? This looks fine. – Louis Wasserman Feb 25 '14 at 20:54

2 Answers2

4

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();
    }
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130