Common Wildcard Mistakes and Compiler Errors
You'll learn to recognize typical wildcard errors and understand what the compiler is telling you when wildcards go wrong.
Wildcards introduce powerful flexibility, but they also create new ways to confuse the compiler—and yourself. The most common mistakes involve trying to write to <? extends T> collections or expecting specific types when reading from <? super T> collections.
The Classic Mistake: Writing to Upper-Bounded Wildcards
The compiler will reject this:
List<? extends Number> numbers = new ArrayList<Integer>();
numbers.add(5); // Compile error: incompatible types
Why it fails: The compiler doesn't know if numbers holds Integer, Double, or some other Number subtype. You can't safely add anything (except null).
Expecting Type Precision from Lower-Bounded Wildcards
This compiles but surprises many beginners:
List<? super Integer> items = new ArrayList<Number>();
Integer value = items.get(0); // Compile error: incompatible types
Why it fails: The compiler only guarantees Object when reading from <? super T>, because the list could be List<Number>, List<Object>, or anything else that's a supertype of Integer.
Mismatching Wildcard Directions
public void copy(List<? extends Number> source, List<? extends Number> dest) {
dest.add(source.get(0)); // Compile error on add()
}
Both parameters use extends, so you can't write to either. The correct signature uses <? super T> for the destination.
Understanding Compiler Messages
Wildcard errors often mention "capture of" or "CAP#1"—this is the compiler's placeholder for the unknown type the wildcard represents. When you see this, you've likely tried an operation the wildcard bounds don't permit.
Key Takeaway:
The most common wildcard mistakes are writing to <? extends T> collections or expecting non-Object types from <? super T> reads; always match your operation (read vs write) to the correct wildcard bound.