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

When to Use Unbounded Wildcards

Identifying scenarios where you only need Collection methods that don't depend on the element type.

When to Use Unbounded Wildcards

What you'll learn: You'll discover when unbounded wildcards (?) are the right choice for working with generic collections.

The Core Idea

Use unbounded wildcards when you're writing code that only needs to call methods that don't depend on the element type of a collection. These are typically operations like checking size, clearing, or iterating without caring about what's inside.

Think of it like a box inspector at a warehouse. If your job is only to count boxes, weigh them, or move them around—without opening them—you don't need to know what's inside. Similarly, unbounded wildcards say "I have a collection of something, but I don't need to know what."

When to Reach for <?>

Use List<?> or Collection<?> when you:

  • Check size() or isEmpty()
  • Call clear() or remove()
  • Iterate with a loop (treating elements as Object)
  • Print or log the collection structure
  • Pass the collection to another method that accepts <?>

You cannot add elements to a Collection<?> (except null), because the compiler doesn't know what type is safe. But you can perform many structural operations safely.

Common Scenario

public static void printSize(List<?> list) {
    System.out.println("Size: " + list.size());
    System.out.println("Empty: " + list.isEmpty());
}

// Works with ANY list type
printSize(new ArrayList<String>());
printSize(new ArrayList<Integer>());
printSize(new ArrayList<MyCustomClass>());

This method doesn't care about element types—it only uses methods that work regardless of what T is.

Key Takeaway: Use unbounded wildcards (?) when your code only needs collection-level operations that don't depend on knowing or manipulating the specific element type—you're working with the container itself, not its contents.