Using a wildcard as a return type implicitly means that the return value should be considered read-only, but without any way to enforce this contract.
Let's take the example of method returning a "List<? extends Animal>". Is it possible on this list to add a Dog, a Cat, ... we simply don't know. The consumer of a method should not have to deal with such disruptive questions.
import java.util.ArrayList;
import java.util.List;
public class S1452 {
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
List<? extends Animal> getAnimals() {
return new ArrayList<>();
}
void check() {
getAnimals().add(new Dog()); // does not compile
getAnimals().add(new Cat()); // does not compile
getAnimals().add(new Animal()); // does not compile
getAnimals().add(null); // OK
}
}
List<Animal> getAnimals() {
return new ArrayList<>();
}
void check() {
getAnimals().add(new Dog()); // OK
getAnimals().add(new Cat()); // OK
getAnimals().add(new Animal()); // OK
getAnimals().add(null); // OK
}
- Do not use wildcard types as return types
- Rather than providing additional flexibility for your users, it would force them to use wildcard types in client code
- If the user of a class has to think about wildcard types, there is probably something wrong with the class’s API