Argument mismatch while using method reference

Viewed 584

The error is :

EmpDemo.java:86: error: no suitable method found for sort(ArrayList,EmpDemo::c[...]BySal) Collections.sort(emp, EmpDemo::compareBySal); ^ method Collections.sort(List) is not applicable (cannot infer type-variable(s) T#1 (actual and formal argument lists differ in length)) method Collections.sort(List,Comparator) is not applicable (cannot infer type-variable(s) T#2 (argument mismatch; invalid method reference cannot find symbol symbol: method compareBySal(T#2,T#2) location: class EmpDemo)) where T#1,T#2 are type-variables: T#1 extends Comparable declared in method sort(List) T#2 extends Object declared in method sort(List,Comparator) 1 error


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 Answers

You don't need a compareBySal() method, simply sort like this:

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

If getSal() returns a float (not obvious from your code), then the following version is even faster:

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

Make compareBySal static in order for it to match the required functional interface:

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

or

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

In your original implementation, where compareBySal is an instance method, EmpDemo::compareBySal requires 3 arguments - an EmpDemo instance and two Employee instances. This doesn't match the Comparator<Employee> interface expected by Collections.sort().

Another alternative (if you don't change compareBySal to be a static method) is to use a method reference of a specific instance:

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