Reputation: 61
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:
Upvotes: 4
Views: 6430
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
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