Wildcard
This lesson talks about how the wildcard can be used in generics.
We'll cover the following...
We'll cover the following...
1.
What is the ?
used for in generics?
0/500
Show Answer
1 / 2
Press + to interact
Java
import java.util.ArrayList;import java.util.Collection;import java.util.List;class Demonstration {public static void main( String args[] ) {Collection<Tiger> tigers = new ArrayList<>();tigers.add(new Tiger());printAnimal(tigers);}static void printAnimal(Collection<? extends Animal> animals) {for (Animal animal : animals)animal.speakUp();}}class Animal {void speakUp() {System.out.println("gibberish");}}class Elephant extends Animal {@Overridepublic void speakUp() {System.out.println("Trumpets..");}}class Tiger extends Animal {@Overridevoid speakUp() {System.out.println("Rooaaarrssss");}}
1.
Will the following method have worked in the previous question for printing a list of type Animal?
static <T extends Animal> void printAnimal(Collection<T> animals) {
for (Animal animal : animals)
animal.speakUp();
}
0/500
Show Answer
1 / 2
Technical Quiz
1.
What happens when we try to compile the following snippet?
Collection<?> myColl = new ArrayList<Object>();
myColl.add(new Object());
A.
Compiles
B.
Compiles with warnings
C.
Doesn’t compile
1 / 1
Press + to interact
Java
import java.util.*;class Demonstration {public static void main( String args[] ) {Collection<?> myColl = new ArrayList<>();// compile time errormyColl.add(new Object());}}
The only element that you can ever insert into a List<?>
...