Berre
Berre

Reputation: 61

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

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

Upvotes: 4

Views: 6430

Answers (2)

Joe C
Joe C

Reputation: 15684

Let's assign types to each of these:

Comparable<T> m = datos.get(menor);
Comparable<T> mj = datos.get(j);
if ((m).compareTo(mj) > 0) { //error line

The Comparable<T> interface expects a T, not a Comparable<T>, as its parameter.

Your signature should instead be:

public static <T extends Comparable<T>> void ordenaSeleccion(List<T> datos)

Upvotes: 3

Harald Gliebe
Harald Gliebe

Reputation: 7554

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

Upvotes: 7

Related Questions