Search⌘ K
AI Features

Wildcard

Explore Java generics focusing on wildcard types. Understand how List<?> accepts only null for insertion and why extraction is limited to Object. Learn about the rules for lower bounds, their use as method arguments, and why they cannot be return types. This lesson equips you to handle wildcard generics confidently in interview scenarios.

We'll cover the following...
1.

What is the ? used for in generics?

Show Answer
1 / 2
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 {
@Override
public void speakUp() {
System.out.println("Trumpets..");
}
}
class Tiger extends Animal {
@Override
void 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();
    }
Show Answer
1 / 2
Technical Quiz
1.

What happens when we try to compile the following Java code?

        Collection<?> myColl = new ArrayList<Object>();
        myColl.add(new Object());
A.

Compiles

B.

Compiles with warnings

C.

Does not compile


1 / 1
Java
import java.util.*;
class Demonstration {
public static void main( String args[] ) {
Collection<?> myColl = new ArrayList<>();
// compile time error
myColl.add(new Object());
}
}

The only element that you can ever insert into a ...