Wildcard
This lesson talks about how the wildcard can be used in generics.
We'll cover the following...
Question # 1
What is the ?
used for in generics?
In generic code, the question mark, ?
, called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable and sometimes even as a return type.
Note that the wildcard can only be used in defining arguments to a method in a method signature. It can't appear in the return type expression.
Question # 2
Can you give an example setup using the ?
wildcard
Imagine we have a class Animal
that has two subtypes Tiger
and Elephant
. The classes are shown below:
public class Animal {
void speakUp() {
System.out.println("gibberish");
}
}
public class Elephant extends Animal {
@Override
public void speakUp() {
System.out.println("Trumpets..");
}
}
public class Tiger extends Animal {
@Override
void speakUp() {
System.out.println("Rooaaarrssss");
}
}
Now imagine we want to write a method that acts on a collection of subtypes of class Animal
. We can write a method like so:
void printAnimal(Collection<Animal> animals) {
for (Animal animal : animals)
animal.speakUp();
}
The above method accepts a collection of type Animal
and we can pass in a collection consisting of objects of type Tiger
like so:
Collection<Animal> tigers = new ArrayList<>();
tigers.add(new Tiger());
printAnimal(tigers);
The problem with the above approach is that we are passing in a collection of type Animal
and we will be unable to pass in a collection of type Tiger
. The below snippet would not compile with our current approach.
Collection<Tiger> tigers = new ArrayList<>();