What is the difference between an extends wildcard and a super wildcard in Java generics?
They look like the opposite of each other, and they are.
An extends wildcard, written as ? extends Animal, means "some type that is an Animal, and I do not know which one". You can read values of that type out of it, and you cannot add anything to it.
A super wildcard, written as ? super Animal, means "some type that an Animal can be put into, and I do not know which one". You can add animals to it, and when you read a value out you only know that it is an Object.
The rule of thumb is easy to remember. A producer extends, and a consumer uses super. A method that hands values out is a producer, and a method that takes values in is a consumer.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Animal> animals = new ArrayList<Animal>();
animals.add(new Dog());
animals.add(new Cat());
// The list of animals is a producer of animals.
printAll(animals);
// The list of objects is a consumer of animals.
List<Object> objects = new ArrayList<Object>();
addAll(objects, animals);
System.out.println("the object list now holds : " + objects);
}
// A producer. The wildcard says that animals may come out.
static void printAll(List<? extends Animal> animals) {
for (Animal animal : animals) {
System.out.println("animal : " + animal.speak());
}
}
// A consumer. The wildcard says that animals may go in.
static void addAll(List<? super Animal> target, List<Animal> source) {
for (Animal animal : source) {
target.add(animal);
}
}
}
class Animal {
String speak() {
return "...";
}
}
class Dog extends Animal {
@Override
String speak() {
return "woof";
}
}
class Cat extends Animal {
@Override
String speak() {
return "meow";
}
}
The next question in this topic looks at what you can actually do with each one.