Writing Restrictions with Unbounded Wildcards
What You'll Learn
You'll discover why collections with unbounded wildcards (List<?>) are essentially read-only—you cannot add elements to them (except null).
The Core Problem
When you declare a collection using an unbounded wildcard like List<?>, the compiler knows the list holds some specific type, but it doesn't know which type. This creates a safety problem for writing.
Think of it like receiving a locked box labeled "Contains items of some type." You can look at what's inside and describe them generically as "objects," but you can't safely put anything new in—because what if you try to add an apple to a box that was meant only for oranges?
Why Writing Fails
List<?> mysteryList = new ArrayList<String>();
// This compiles:
Object obj = mysteryList.get(0); // Reading is safe
// This does NOT compile:
// mysteryList.add("Hello"); // ERROR!
// mysteryList.add(new Object()); // ERROR!
// Only this compiles:
mysteryList.add(null); // null is a member of every type
The compiler rejects your add() attempts because:
List<?>could beList<String>,List<Integer>,List<Cat>—anything!- You can't add a
Stringto a potentialList<Integer> - You can't even add
Objectbecause the list might beList<String>, andObjectisn't safely aString
Only null works because it's a valid value for any reference type.
The Analogy
It's like being handed a sealed donation box labeled "Accepts one specific type of item only—guess which!" You wouldn't dare drop anything in, because you might contaminate a toy donation with food, or vice versa.
Key Takeaway: Collections with unbounded wildcards (?) are effectively read-only; you cannot add elements except null because the compiler cannot verify type safety without knowing the actual type.