Error when implementing comparable generic list


I'm trying to compare the values within my nodes with the Comparable interface. But when implementing the method compareTo I get an error: It says that the operator can not be applied to <E> (which is my generic value).

I leave you code:

public class LEGultimoEC<E> extends LEGultimo<E> implements Comparable<NodoLEG<E>> {

    public LEGultimoEC(NodoLEG<E> primero, NodoLEG<E> ultimo) {

    public int compareTo(NodoLEG<E> o) {
        int resultado = 0;
            return -1;
        }else if(o.getDato()>o.getSiguiente().getDato()){
            return  1;

The value in data is int .

asked by Peter 30.03.2018 в 23:46

2 answers


The type parameter E has no restriction in your class LEGultimoEC<E> so it can be any class, even just Object .

The operator < and > can only be occupied in primitive numeric types ( byte , short , int , long , char , float , double ) or in those types that can be converted via unboxing to those types.

Therefore it will never be valid to compare:

E e1 = ...
E e2 = ...
if(e1 < e2) {...}

For that to be possible you would have to set some upper limit (in English upper bound ) to that parametric type that allows you to use the operator, in the following way:

class LEGultimoEC<E extends Integer>

With that, you could already use the operator and you could write LEGultimoEC<Integer> . But it would not do you much good since you could only parameterize with Integer and nothing else ( Integer is final).

The most useful form is the one that suggests @dmmiralles , instead of restricting to some class in which you can use the operator, restricts to Comparable :

class LEGultimoEC<E extends Comparable<E>>

With that, instead of using the operator, you use:

E e1 = ...
E e2 = ...
if(e1.compareTo(e2) < 0) {...}

The definition of your class would then be somewhat more extensive:

public class LEGultimoEC<E extends Comparable<E>>
    extends LEGultimo<E> implements Comparable<NodoLEG<E>> {
answered by 31.03.2018 / 02:58

For this you must take into account 2 things:

  • At compile time it is not known that E is an integer, therefore the operator '<' can not be applied to compare, for that you must use the compareTo method of Comparable.

  • To be able to compliment point 1, you must make sure that the generic E inherits from Comparable (Restricted Genericity).

  • answered by 31.03.2018 в 00:01