Video in progress
Why can't you pass a `List<Dog>` to a method that expects a `List<Animal>`, and how do you make an API flexible with wildcards?
Generics are invariant: List<Dog> is not a subtype of List<Animal>, otherwise you could add a Cat to it. In APIs you apply the PECS rule: a parameter you only read from is ? extends T, one you only write to is ? super T.
📖 Answer
void feedAll(List<Animal> animals) { ... }
List<Dog> dogs = ...;
feedAll(dogs); // compile error
If this were allowed, feedAll could do animals.add(new Cat()) and a cat would appear in the dogs list.
PECS stands for "Producer Extends, Consumer Super":
// only reads (producer)
void feedAll(Collection<? extends Animal> animals) {
for (Animal a : animals) a.feed();
}
// only writes (consumer)
void addDefaults(Collection<? super Dog> target) {
target.add(new Dog("Rex"));
}
// both
static <T> void copy(List<? super T> dst, List<? extends T> src) { ... }
The JDK does this everywhere: Collections.copy, List.sort(Comparator<? super E>), Stream.flatMap(Function<? super T, ? extends Stream<? extends R>>).
Practical rules:
- use wildcards in parameters, not in return types: returning
List<? extends Animal>makes life awkward for the caller; Comparator<? super T>is almost always right: anAnimalcomparator can sortDogs too;- if a parameter is both read and written, keep a plain
T.
A common interview follow-up: why does this work with arrays? Because arrays are covariant and catch the mistake at runtime (ArrayStoreException).
Sign up to mark studied questions and save your progress.