为什么我的compare()方法不能引用模型类字段或方法?

时间:2014-11-10 18:35:02

标签: java compare comparator

我确实使用name和getSalary()方法定义了Employee类,但是当我定义MyComparator时,它将emp1和emp2识别为Employee类 但不会识别name和getSalary()方法(dundefined)。

import java.util.Comparator;

public class MyComparator<Employee> implements Comparator<Employee> {

    @Override
    public int compare(Employee emp1, Employee emp2) {

        String s = emp1.name;

        if (emp1.getSalary() < emp2.getSalary()) {
            return -1;
        } else if (emp1.getSalary() == emp2.getSalary()) {
            return 0;
        } else
            return 1;

    } // compare method

} // MyComparator class

public class Employee {

    private int salary;
    public String name;

    Employee(String n, int s) {
        salary = s;
        name = n;
    }

    public int getSalary() {
        return salary;
    }
}

1 个答案:

答案 0 :(得分:0)

正确的语法是:

public class MyComparator implements Comparator<Employee> {

@Override
public int compare(Employee emp1, Employee emp2) {

    String s = emp1.name;

    if (emp1.getSalary() < emp2.getSalary()) {
        return -1;
    } else if (emp1.getSalary() == emp2.getSalary()) {
        return 0;
    } else
        return 1;

   } // compare method

}

您必须将MyComparator<Employee>替换为MyComparator

您实际上是在定义一个新的泛型,而不是使用比较器创建的泛型。