0

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

}

1 Answer 1

1

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) {
    ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer, it made me understand a couple things better. Unfortunately I get the same compilation error on the line where sort gets called. I should point out it happens only when explicitly writing parameter types. If I don't do it it doesn't allow me to use Person::getAge() tho.
Hm, I dunno. It compiled for me when I fixed these two errors.
@AleksanderBarański it should work, see here: onlinegdb.com/l98XF5ftx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.