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

Writing Restrictions with Unbounded Wildcards

Understanding why you cannot add elements (except null) to collections with unbounded wildcards.

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 be List<String>, List<Integer>, List<Cat>—anything!
  • You can't add a String to a potential List<Integer>
  • You can't even add Object because the list might be List<String>, and Object isn't safely a String

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.