fireflieslive fireflieslive - 2 years ago 79
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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download