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

Common Capture Conversion Pitfalls

Understanding when capture conversion fails and how to recognize 'capture of ?' compiler errors.

Common Capture Conversion Pitfalls

You'll learn: how to recognize when capture conversion fails and what those cryptic "capture of ?" compiler errors really mean.

While capture conversion is a powerful technique for working with wildcards, it has limits. Understanding when it breaks down will save you from confusing compiler messages and help you write better generic code.

When Capture Conversion Fails

The most common pitfall occurs when you try to relate two different wildcards in a single operation. Remember, each wildcard ? represents an unknown but specific type, and the compiler treats each occurrence as a potentially different type.

// This FAILS with "capture of ?" error
public static void badSwap(List<?> list1, List<?> list2) {
    Object temp = list1.get(0);
    list1.set(0, list2.get(0)); // ❌ Compiler error!
    list2.set(0, temp);         // ❌ Compiler error!
}

The compiler sees list1 as List<capture#1 of ?> and list2 as List<capture#2 of ?>. It cannot guarantee that capture#1 and capture#2 are the same type, so it rejects the swap.

Recognizing the Error

When you see messages like:

  • "incompatible types: capture#1 of ? cannot be converted to capture#2 of ?"
  • "method set(int,CAP#1) cannot be applied to CAP#2"

You've hit a capture conversion limitation. Each wildcard gets its own independent "capture" variable.

The Fix: Explicit Type Parameters

Use a type parameter to enforce that both lists have the same element type:

public static <T> void goodSwap(List<T> list1, List<T> list2) {
    T temp = list1.get(0);
    list1.set(0, list2.get(0)); // ✓ Works!
    list2.set(0, temp);          // ✓ Works!
}

Key Takeaway: Capture conversion fails when multiple wildcards must relate to each other; use explicit type parameters instead of wildcards when operations need to coordinate types across multiple generic structures.