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

Wildcard Capture and Reading from <?> Collections

Learn what operations are allowed on collections with unbounded wildcards and why you can read but not write.

Wildcard Capture and Reading from <?> Collections

What You'll Learn

You'll discover what operations are safe to perform on collections declared with the unbounded wildcard <?> and understand why reading is allowed but writing isn't.

Why You Can Read But Not Write

When you declare a collection with an unbounded wildcard like List<?>, you're saying "this is a list of some unknown type." Java doesn't know what that type is—it could be List<String>, List<Integer>, or List<Number>.

Reading is safe because anything you pull out can safely be treated as Object (Java's universal supertype). No matter what the actual type is, everything in Java is an Object.

Writing is dangerous because Java can't verify type safety. If you had a List<String> assigned to List<?>, and Java let you add an Integer, you'd corrupt the list. So Java blocks all additions except null (which is compatible with every reference type).

Reading Example

List<?> mysteryList = new ArrayList<String>();
// mysteryList now holds a List<String>, but we only know it's List<?>

Object item = mysteryList.get(0); // ✅ Safe! Anything is an Object
// String s = mysteryList.get(0); // ❌ Won't compile—could be List<Integer>

// mysteryList.add("hello"); // ❌ Won't compile—can't add anything
// mysteryList.add(42);      // ❌ Won't compile
mysteryList.add(null);       // ✅ null is always allowed

The Analogy

Think of List<?> as a locked box labeled "Contains items, but I won't tell you what kind." You can safely peek inside and call everything "a thing," but you can't add anything because you don't know what belongs in there.

Key Takeaway: Collections with unbounded wildcards (<?>) allow reading as Object but prohibit adding elements (except null) because the actual type is unknown—preserving type safety at compile time.