Search⌘ K
AI Features

Bounded Types and Wildcards

Explore how to restrict generic types in Java using bounded types and wildcards. Understand the PECS principle for producer-extends and consumer-super, enabling safe reading and writing in collections. Master wildcard capture to swap elements generically. This lesson helps you write flexible and type-safe generic code crucial for reusable libraries and solving common Java interview questions.

We'll cover the following...

When we create generic classes or methods, we often want to restrict the types that can be used as arguments. For example, a math utility class should only accept numbers, not strings. Java provides bounded types and wildcards to give us precise control over what types our generics will accept, ensuring type safety while maintaining flexibility.

Let's look at the common interview questions.

AI Powered
Saved
10 attempts left
Reset
Question

What are bounded type parameters?

You have 10 attempts to answer.

We can see how bounding a type parameter prevents runtime errors and allows us to use specific methods of the bounded class without casting.

Java
import java.util.ArrayList;
import java.util.List;
class NumberCollection<T extends Number> {
List<T> list = new ArrayList<>();
public void add(T item) {
list.add(item);
}
public void printGreater(T other) {
for (T item : list) {
if (item.intValue() > other.intValue()) {
System.out.println(item);
}
}
}
}
class Program {
public static void main(String[] args) {
NumberCollection<Integer> myIntegerList = new NumberCollection<>();
myIntegerList.add(5);
myIntegerList.add(4);
myIntegerList.printGreater(4);
// NumberCollection<String> invalidList = new NumberCollection<>(); // Compile error
}
}
  • Line 5: We declare <T Number extends> ...