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>>
.E.g.
Integer
implementsComparable<Integer>
, which is not compatible withComparable<? 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 ofNumber
, and passing aT
tocompareTo
would then not compile because it expects a parameter of?
, notT
.Edit: as newacct said,
<T extends Number & Comparable<? super T>>
will work too (and be slightly more general) since thencompareTo
will then accept any?
of whichT
is a subclass, and as usual, an instance of a subclass can be given as a parameter where a superclass is expected.