Wildcard generics in Java provide a powerful way to increase the flexibility of generic types. They allow you to work with unknown types, making your code more versatile and reusable.
Wildcard generics use the question mark (?
) symbol to represent an unknown type. They're particularly useful when you want to write methods that can operate on collections of different types.
<?>
<? extends Type>
<? super Type>
An unbounded wildcard is useful when you want to work with objects of unknown type:
public void printList(List<?> list) {
for (Object item : list) {
System.out.println(item);
}
}
Upper bounded wildcards restrict the unknown type to be a specific type or a subtype of that type:
public double sumOfList(List<? extends Number> list) {
double sum = 0.0;
for (Number num : list) {
sum += num.doubleValue();
}
return sum;
}
Lower bounded wildcards specify that the unknown type must be a supertype of a specific type:
public void addNumbers(List<? super Integer> list) {
for (int i = 1; i <= 10; i++) {
list.add(i);
}
}
Wildcard generics are closely related to Java Generic Classes and Java Generic Methods. Understanding these concepts will help you write more flexible and type-safe Java code.
Mastering wildcard generics in Java enhances your ability to write flexible, reusable code. They're particularly valuable when working with collections and APIs that need to handle multiple types. As you continue to explore Java, consider diving deeper into related topics like Java Bounded Type Parameters to further expand your knowledge of generics.