Aleksander Barański
Aleksander Barański

Reputation: 11

Incompatible parameter types in lambda expression in custom sorting function comparator

I am making a custom sorting function as an excercise for uni.

package com.mycompany.sortowanie;
public interface Comp<T>{
     <T> boolean compare(T o1, T o2);
}

and

package com.mycompany.sortowanie;

import java.util.LinkedList;

public class MaszynaSortujaca<T> {
   public void sort(LinkedList<T> arr, Comp cmp) {
       for(int i = 0; i < arr.size()-1; i++) {
            for(int j = 0; j < arr.size()-i-1; j++) {
                if(cmp.compare(arr.get(j), arr.get(j+1))) {
                    T temp = arr.get(j);
                    arr.set(j, arr.get(j+1));
                    arr.set(j+1, temp);
                }
            }
        } 
    }
}

Please ignore the bits of polish language in here. Whenever I try to use a function on some class it gives me "incompatible parameter types in lambda expression" compilation error, like this:

m.sort(p, (Person n1, Person n2) -> {return n1.getAge() < n2.getAge();});

I don't understand why they are considered incompatible parameter types and I don't know what to do at this stage. Here is the code of the Person class in case anyone needs that:

package com.mycompany.sortowanie;

public class Person{
    private final String name;
    private final int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public int getAge() {
        return age;
    }
    public String getName() {
        return name;
    }

}

Upvotes: 0

Views: 210

Answers (1)

John Kugelman
John Kugelman

Reputation: 361879

First problem, the compare() method should not have its own <T> variable. Writing <T> there shadows the one from Comp<T>, creating a different type variable with the same name. Remove it:

public interface Comp<T> {
    boolean compare(T o1, T o2);
}

Second problem, in the sort() function Comp cmp is missing <T>. Make sure both the linked list and the comparator have <T> so there are no raw types:

public void sort(LinkedList<T> arr, Comp<T> cmp) {
    ...
}

Upvotes: 1

Related Questions