问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/7966051/static-t-extends-number-comparable-super-number