使用方法参考时参数不匹配

时间:2018-12-19 13:27:55

标签: java sorting lambda java-8 method-reference

错误是:

  

EmpDemo.java:86:错误:找不到适合的方法   sort(ArrayList,EmpDemo :: c [...] BySal)Collections.sort(emp,   EmpDemo :: compareBySal);                    ^       方法Collections.sort(List)不适用         (无法推断类型变量T#1           (实际和正式参数列表的长度不同)       方法Collections.sort(List,Comparator)不适用         (无法推断类型变量T#2           (参数不匹配;方法参考无效             找不到标志               符号:方法compareBySal(T#2,T#2)               位置:类EmpDemo)),其中T#1,T#2是类型变量:       T#1扩展了在方法sort(List)中声明的Comparable       T#2扩展了在方法sort(List,Comparator)中声明的对象    1个错误


public class EmpDemo {

    int compareBySal(Employee e1,Employee e2) {
        return (int) (e1.getSal()-e2.getSal());
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        ArrayList<Employee> emp=new ArrayList<Employee>();

        //Adding employees
        for(int i=1;i<3;i++)
        {

            System.out.println("----Enter the  " +i +"TH Data------");
            System.out.println("Enter your salary");
            float sal=sc.nextFloat();

            Employee e=new Employee();
            e.setSal(sal);

            emp.add(e);
            System.out.println();

        }

        //displaying the employees
        System.out.println("Before Sorting.....");
        System.out.println(emp);

        //**Using METHOD REFERENCE**
        Collections.sort(emp, EmpDemo::compareBySal);

        System.out.println("Before Sorting.....");
        System.out.println(emp);
    }
}

2 个答案:

答案 0 :(得分:0)

您不需要compareBySal()方法,只需进行如下排序:

Collections.sort(emp, Comparator.comparing(Employee::getSal));

如果getSal()返回float(在您的代码中不明显),则以下版本会更快:

Collections.sort(emp, Comparator.comparingDouble(Employee::getSal));

答案 1 :(得分:0)

制作compareBySal static使其与所需的功能接口匹配:

static int compareBySal(Employee e1,Employee e2) 
{
    return (int) (e1.getSal()-e2.getSal());
}

static int compareBySal(Employee e1,Employee e2) 
{
    return Float.compare(e1.getSal(),e2.getSal());
}

在您的原始实现中,compareBySal是实例方法,EmpDemo::compareBySal需要3个参数-一个EmpDemo实例和两个Employee实例。这与Comparator<Employee>期望的Collections.sort()接口不匹配。

另一种选择(如果不将compareBySal更改为static方法)是使用特定实例的方法引用:

Collections.sort(emp, new EmpDemo()::compareBySal);