Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error incompatible types: Comparable<T> cannot be converted to T

Tags:

java

I'm not sure what is going on. The method works pereclty with an array but if I use a list... well.

I really hope you can help me.

public static <T> void ordenaSeleccion(List<? extends Comparable<T>> datos)
{
    Object aux;
    int menor;

    for (int i = 0; i < datos.size(); i++) {
        menor = i;

        for (int j = i + 1; j < datos.size(); j++) {
            if (datos.get(menor).compareTo(datos.get(j)) > 0) { //error line
                menor = j;
            }
        }

        if (menor != i) {
            aux = datos.get(i);
            datos.set(i, datos.get(menor));
            datos.set(menor, aux);
        }

    }
}

this is the error:

enter image description here

like image 453
Berre Avatar asked Dec 24 '22 14:12

Berre


1 Answers

List<? extends Comparable<T>> only says that the elements of the list can be compared with instances of T, not that they are subclasses of T. That's why you get your error message.

Could you change your implementation as follows:

public static <T extends Comparable<T>> void ordenaSeleccion(List<T> datos)
{
    T aux;
    int menor;

    for (int i = 0; i < datos.size(); i++) {
        menor = i;

        for (int j = i + 1; j < datos.size(); j++) {
            if (datos.get(menor).compareTo(datos.get(j)) > 0) { //error line
                menor = j;
            }
        }

        if (menor != i) {
            aux = datos.get(i);
            datos.set(i, datos.get(menor));
            datos.set(menor, aux);
        }
    }
}
like image 83
Harald Gliebe Avatar answered May 08 '23 06:05

Harald Gliebe