You might know that the predicates are compatible, but the compiler does not.
Imagine this example:
Predicate<? extends Collection<Object>> p1 = (Set<Object> s) -> s.isEmpty();
Predicate<? extends Collection<Object>> p2 = (List<Object> l) -> l.get(0) != null;
We developers can see that the first predicate could technically handle all collections, while the second one can handle only lists. But imagine the predicates were initialized somewhere else or would be changed in the meantime. The compiler cannot know for sure which type of collections the predicate objects were made for. As a result, you cannot use them at all:
Set<Object> set = new HashSet<>();
List<Object> list = new ArrayList<>();
p1.test(set);
p2.test(list);
p1.test(list);
p2.test(set);
All these calls won't compile, because the compiler cannot say whether the actual objects behind p1
and p2
can are exactly for those types of collections. That is the meaning of ? extends Collection<>
: You know it is a specific sub type, but you cannot tell the compiler which one exactly.
To illustrate this with a simpler example:
Collection<Apple> appleBasket = ...;
appleBasket.add(new Apple()); // works
appleBasket.add(new Orange()); // does not work (obviously)
Collection<Fruit> mixedFruitBasket = ...;
mixedFruitBasket.add(new Apple()); // works
mixedFruitBasket.add(new Orange()); // works
// Now the tricky part
Collection<? extends Fruit> unknownButPureFruitBasket = ...;
unknownButPureFruitBasket.add(new Apple()); // does not work
unknownButPureFruitBasket.add(new Orange()); // does not work
You cannot add any one fruit to a basket whose type you don't know. It could in fact be a basket that accepts all fruit, but it could be a pure Apple basket, or Orange backet, or even a Banana basket that you do not even know of yet.
Try it in your IDE:
List<? extends String> l1 = new ArrayList<>();
List<? extends String> l2 = new ArrayList<>();
l1.addAll(l2);
Eclipse tells me:
The method addAll(Collection1-of ? extends String>) in the type List<capture#1-of ? extends String> is not applicable for the arguments (List<capture#2-of ? extends String>)
Note the different types: addAll
expects a collection of capture#1
, l2
is a collection of capture#2
.