Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static <T extends Number & Comparable<? super Number>>

I have following class with one static method:

public class Helper {

    public static <T extends Number & Comparable<? super Number>> Boolean inRange(T value, T minRange, T maxRange) {
        //  equivalent (value >= minRange && value <= maxRange)
        if (value.compareTo(minRange) >= 0 && value.compareTo(maxRange) <= 0)
            return true;
        else
            return false;
    }

}

I try to call this method:

Integer value = 2;
Integer min = 3;
Integer max = 8;
Helper.inRange(value, min, max) ;

Netbeans compiler show me this error message:

method inRange in class Helper cannot be applied to given types; required: T,T,T found: java.lang.Integer,java.lang.Integer,java.lang.Integer reason: inferred type does not conform to declared bound(s) inferred: java.lang.Integer bound(s): java.lang.Number,java.lang.Comparable

Any ideas?

thanks.

like image 995
misco Avatar asked Nov 01 '11 11:11

misco


1 Answers

Try <T extends Number & Comparable<T>>.

E.g. Integer implements Comparable<Integer>, which is not compatible with Comparable<? super Number> (Integer is not a superclass of Number). Comparable<? extends Number> would not work either because Java would then think the ? could be any subclass of Number, and passing a T to compareTo would then not compile because it expects a parameter of ?, not T.

Edit: as newacct said, <T extends Number & Comparable<? super T>> will work too (and be slightly more general) since then compareTo will then accept any ? of which T is a subclass, and as usual, an instance of a subclass can be given as a parameter where a superclass is expected.

like image 98
mpartel Avatar answered Sep 17 '22 04:09

mpartel