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



错误为:

EmpDemo.java:86:错误:没有找到适合排序(ArrayList,EmpDemo::c[…]BySal(Collections.sort(emp,EmpDemo::compareBySal(;^方法Collections.sort(List(不适用(无法推断类型变量T#1(实际参数列表和正式参数列表的长度不同(方法Collections.sort(List,Comparator(不适用(无法推断类型变量T#2(参数不匹配;方法引用无效找不到符号symbol:方法compareBySal(T#2,T#2(location:class EmpDemo((,其中T#1、T#2是类型变量:T#1扩展了在方法排序(List(中声明的ComparableT#2扩展在方法排序(List,Comparator(中声明的Object1个错误


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

使compareBySalstatic匹配所需的功能接口:

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实例。这与Collections.sort()所期望的Comparator<Employee>接口不匹配。

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

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

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

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

如果getSal()返回float(从代码中看不出来(,那么下面的版本会更快:

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

最新更新