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

Reading from Unbounded Wildcard Collections

Why elements from List<?> can only be assigned to Object and what operations are safe to perform.

Reading from Unbounded Wildcard Collections

What you'll learn: You'll understand why elements from a List<?> can only be safely assigned to Object and which operations you can perform on unbounded wildcard collections.

The Core Problem

When you have a collection with an unbounded wildcard like List<?>, Java knows it's a list of something, but it doesn't know what. It could be List<String>, List<Integer>, or List<MyCustomClass>. Since Java can't guarantee the specific type, it must be extremely conservative about what you can do with elements you read from it.

Why Everything Becomes Object

When you read an element from List<?>, the compiler asks: "What type do all possible types have in common?" The answer is always Object—Java's universal superclass. This is the only safe guarantee.

List<?> mysteryList = new ArrayList<String>();
Object element = mysteryList.get(0); // ✓ Safe
// String str = mysteryList.get(0);  // ✗ Compile error!

Even though you might know it's a List<String>, the compiler doesn't, and it won't let you assume.

Safe Operations on List<?>

You can safely:

  • Read elements as Object
  • Check the size: mysteryList.size()
  • Check if empty: mysteryList.isEmpty()
  • Remove elements: mysteryList.remove(element) or mysteryList.clear()
  • Iterate (elements come out as Object)

You cannot:

  • Add non-null elements (except null itself, since null belongs to every reference type)
  • Assign elements to anything more specific than Object

Key Takeaway: Elements from List<?> can only be read as Object because the compiler doesn't know the actual type parameter. You can perform null-safe operations like size checks and removal, but type-specific operations require knowing the concrete type argument.