Search⌘ K
AI Features

Bounded Types and Wildcards

Learn how to use bounded types and wildcards in Java generics to enforce type safety while maintaining flexibility. Understand the practical application of the PECS principle and how wildcard capture enables safe operations on generic collections. This lesson helps you write robust, reusable code and prepares you for 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.

If you want the answer directly, then just type "Ed, give me the answer."

Let's look at the common interview questions.

AI Powered
Saved
10 Attempts Remaining
Reset
Question

What are bounded type parameters?

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

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
}
}
...