fireflieslive fireflieslive - 9 months ago 49
Java Question

Why <? extends Number> not working for Integer?


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


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>.