Raw Types vs Unbounded Wildcards
What you'll learn: You'll understand the crucial difference between List (raw type) and List<?> (unbounded wildcard), and why one is type-safe while the other isn't.
The Core Distinction
Both List and List<?> appear to accept any type of list, but they behave very differently when it comes to type safety.
A raw type like List completely bypasses generic type checking. The compiler treats it like the pre-generics era—it allows you to add any object, assuming you know what you're doing. This is dangerous because you can corrupt the list's actual type.
An unbounded wildcard like List<?> means "a list of some specific unknown type." The compiler enforces safety by preventing you from adding anything (except null) because it doesn't know what type the list actually holds.
Why This Matters
List rawList = new ArrayList<String>();
rawList.add(42); // Compiles with warning—disaster waiting to happen!
List<?> wildcardList = new ArrayList<String>();
// wildcardList.add(42); // Compile error—protected!
wildcardList.add(null); // Only null is allowed
With the raw type, you can accidentally insert an Integer into what's actually a String list. With the wildcard, the compiler blocks all insertions, keeping the list safe.
Reading from both is possible, but raw types return Object with no warnings, while wildcards explicitly acknowledge the unknown type.
The Analogy
Think of a raw type as an unlocked safety box—you can put anything in, risking chaos. An unbounded wildcard is a sealed box with a viewing window—you can see what's inside, but you can't add anything without knowing the exact combination (the actual type).
Key Takeaway: Always prefer List<?> over raw List when you need to work with a generic type of unknown parameter—wildcards preserve type safety while raw types abandon it entirely.