Capture Conversion in Action
You'll learn how capture conversion enables operations on wildcard types that initially seem impossible.
The Problem Wildcards Create
When you have a List<?>, the compiler doesn't know what specific type it holds. This normally prevents you from adding elements (except null) because the compiler can't verify type safety. It seems like wildcards create a dead-end for certain operations.
How Capture Conversion Helps
Capture conversion is a compiler mechanism that temporarily "captures" the unknown wildcard type as a fresh type parameter. This happens automatically when you pass a wildcard collection to a helper method.
Here's the pattern in action:
public void reverse(List<?> list) {
reverseHelper(list); // Capture conversion happens here
}
private <T> void reverseHelper(List<T> list) {
// Now we have a real type parameter T
// We can safely move elements around
if (list.size() < 2) return;
T first = list.get(0);
T last = list.get(list.size() - 1);
list.set(0, last);
list.set(list.size() - 1, first);
}
The wildcard ? in reverse() gets "captured" as the type parameter T when calling reverseHelper(). The compiler now knows that all elements have some consistent type, even if it doesn't know exactly what that type is.
Why This Works
The key insight: while the compiler doesn't know the specific type, it knows there is one consistent type. By capturing it as T, operations that shuffle existing elements become safe—you're not adding anything new, just rearranging what's already there.
Key Takeaway: Capture conversion allows you to bridge from wildcard types to proper type parameters by delegating to a generic helper method, enabling operations that require type consistency without knowing the exact type.