The Unbounded Wildcard: ? Basics
What you'll learn: You'll understand what <?> means, when to use unbounded wildcards, and how they differ from raw types and Object.
What Is the Unbounded Wildcard?
The unbounded wildcard <?> (pronounced "wildcard of unknown type") represents any type parameter, but in a type-safe way. When you write List<?>, you're saying "this is a List of some specific type, but I don't know or care what that type is right now."
How It Differs from Raw Types and Object
At first glance, List<?>, raw List, and List<Object> might seem similar, but they're fundamentally different:
- Raw type (
List): Abandons type safety entirely. Compiler warnings everywhere. You can add anything, risking runtime errors. List<Object>: A list specifically ofObjectreferences. AList<String>is not aList<Object>(generics aren't covariant).List<?>: A list of unknown but specific type. Type-safe, but you can't add elements (exceptnull) because the compiler doesn't know what type is allowed.
When to Use Unbounded Wildcards
Use <?> when you:
- Need to accept any parameterized type
- Only need to read elements as
Objector call type-independent methods - Want type safety without knowing the specific type parameter
Think of it like a locked box: you know there's something inside, but since you don't know what, you can't safely put anything in. You can only observe or use generic operations.
public void printListSize(List<?> list) {
System.out.println(list.size()); // Safe: size() works on any List
// list.add("text"); // COMPILE ERROR: unknown type
}
Key Takeaway: <?> provides type-safe handling of generics when you don't need to know the specific type—far safer than raw types, and more flexible than Object.