java – What does it mean<T extends Comparable> …?

Question:

public static <T extends Comparable> T getMenor(T[] a) {

    if (a.length <= 1 || a == null) {
        return null;
    }

    T menorElemento = a[0];

    for (int i=1; i<a.length; i++) {

        if (menorElemento.compareTo(a[i]) > 0 ) {//Si menorEle es mayor a a[i], entonces el menor es a[i]
            menorElemento = a[i];
        }

    }

    return menorElemento;
}

I understand that the method receives a parameter of type T (generic). What I don't understand is this part:

T extends Comparable

What does it mean? Could someone explain it to me?

Answer:

<T extends Comparable> means that the compile-time method defines a generic variable type but the class or interface must implement or extend the Comparable interface. This restricts the clients' use of this method.


It should be noted that the method has a problem: it indicates that the generic class / interface should implement / extend of Comparable but does not restrict the class to be Comparable of itself. That is, this code would be valid:

public class Bar { }
public class Foo implements Comparable<Bar> {
    @Override
    public int compareTo(Bar b) {
        //implementación descabellada, no utilizar
        //en código de producción
        return 0;
    }
}

//...

Foo[] arrayFoo = ...;
Foo menor = getMenor(arrayFoo); //compila y corre sin problemas

To correct this error, the generic should be declared like this:

<T extends Comparable<? super T>>
Scroll to Top