fireflieslive fireflieslive - 6 months ago 18
Java Question

Why <? extends Number> not working for Integer?

Why

Predicate<? super Integer> isGreaterThanZero = num -> num.intValue() > 0;


works for

isGreaterThanZero.test( new Integer( 2 ));


and not

Predicate<? extends Number> isGreaterThanZero = num -> num.intValue() > 0;


I see them as the same since
Integer
is-a
Number

Answer

When you declare Predicate<? extends Number> isGreaterThanZero, you are telling the compiler that isGreaterThanZero is a Predicate parametrized by some unknown subtype of Number.

As far as the compiler knows, it could be a Predicate<Double> or a Predicate<BigInteger>. Can you safely pass an Integer to an object that might be Double or BigInteger? You cannot. The only thing that you can pass to such an object is null.

If you want isGreaterThanZero to be a predicate that works on any subtype of Number, you should declare it as Predicate<Number>.

Comments