简体   繁体   中英

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.

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

Eg Integer implements Comparable<Integer> , which is not compatible with Comparable<? super Number> Comparable<? super Number> (Integer is not a superclass of Number). Comparable<? extends 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>> <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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM