I want to create a simple generic method to count the numbers
after applying the filter based on the provided predicate
.
static int count(Collection < ? extends Number > numbers, Predicate < ? extends Number > predicate) {
return numbers.stream().filter(predicate).count();
}
It gives me the following error:
incompatible types: Predicate cannot be converted to
Predicate<? super CAP#2>
where CAP#1, CAP#2 are fresh type-variables:CAP#1 extends Number from capture of ? extends Number
CAP#2 extends Number from capture of ? extends Number
Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements.
Generic MethodsAll generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas.
You can't use the wildcard like this, as the second parameter depends on the first one! Your version implies that you want to take a Collection of Apples to then apply a Banana Predicate on that.
In other words: simply declare a not-unkown type parameter; and use that:
static <T extends Number> long count(Collection<T> numbers, Predicate <T> predicate) {
For the record: count()
returns a long result; thus I changed the return type accordingly. If that is not what you want, you have to cast to int, but live with the (potential) loss of information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With