Course contentsShow
← Java
Lesson 956 of 2,87022. Generics: Bounds and WildcardsFree lesson

Capture Helper Methods Pattern

Creating private helper methods with type parameters to work around wildcard limitations using capture.

Capture Helper Methods Pattern

What you'll learn: How to create private helper methods with type parameters to safely work around wildcard limitations using capture conversion.

The Problem with Wildcards

You've learned that wildcards like ? are powerful but limited—you can't call methods that need to know the specific type because the compiler treats ? as an unknown type. This creates frustrating situations where you know an operation is safe, but the compiler won't let you do it directly.

The Capture Helper Pattern

The capture helper method pattern is a technique where you create a private generic helper method that "captures" the unknown wildcard type into a concrete type parameter. This helper then performs the operation safely.

Here's how it works:

public void swapFirst(List<?> list1, List<?> list2) {
    // Can't do: list1.set(0, list2.get(0)) — types don't match!
    swapHelper(list1, list2);  // Delegate to helper
}

private <T> void swapHelper(List<T> list1, List<T> list2) {
    T temp = list1.get(0);     // Type T is captured
    list1.set(0, list2.get(0)); // Now compiler knows both lists have same type
    list2.set(0, temp);
}

Think of it like this: The wildcard ? is like a locked box—you know something's inside, but can't use it. The helper method is like a master key that opens the box and gives the contents a proper name (T), letting you work with it safely.

Why It Works

When you call swapHelper(list1, list2), the compiler performs capture conversion: it infers that both wildcards represent the same concrete type for that specific call, binding it to T. Inside the helper, T is a real type parameter you can use normally.

Key Takeaway:
Use private generic helper methods to capture wildcard types into concrete type parameters, enabling operations the compiler would otherwise reject—this pattern bridges the gap between wildcard flexibility and type-safe operations.