Search code examples
javalistcomparable

Collection.sort with LinkedList Comparable method already overrided


I tried to sort my linkedlist using the Collection.sort method and I get this error:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ListIndiv). The inferred type Individu is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>"

I tried to do some research on it but I didn't find an answer to my problem.

List indiv class:

public class ListIndiv extends LinkedList<Individu> 
    implements Comparable<Individu> {
    //some code
    @Override
    public int compareTo(Individu i1, Individu i2) {
        return peek().distance(i1) - peek().distance(i2);
    }

Main class:

public class Main {
    public static void main(String[] args) {

        Individu i1 = new Individu();
        i1.age = 4; i1.couleur_yeux = Color.green;
        Individu i2 = new Individu();
        i2.age = 16; i2.couleur_yeux = Color.blue;
        Individu i3 = new Individu();
        i3.age = 24; i3.couleur_yeux = Color.black;

        ListIndiv li = new ListIndiv();

        li.add(i1);li.add(i2);li.add(i3);

        Collections.sort(li);
    }
}

The line

Collection.sort(li);

is causing the problem.. I have no idea what I did wrong.


Solution

  • What should be comparable is not the ListIndividu but the Individu class itself (you are not comparing lists, you are comparing Individus in the list). Move the "Comparable" & related method to your Individu class.