Generic
Wildcards in Java
Master the <?> and <? extends T> syntax to write flexible, type-safe methods that work with families of generic types.
What Are Generics?
Generics let you write classes and methods that work with any type while keeping full compile-time type safety. Instead of casting from Object, you declare a type parameter like <T>.
The Problem Wildcards Solve
You might expect a List<Dog> to be assignable to a List<Animal> because Dog extends Animal. But in Java, generics are invariant: they do not follow the same inheritance rules as their type arguments.
Introducing <?>
The wildcard symbol ? stands for "some unknown type." It lets you declare a reference that can point to a generic container of any type argument.
The Three Wildcard Forms
Unbounded: <?>
Upper-Bounded: <? extends T>
<T> vs <?>: Key Distinction
| <T> Type Parameter | <?> Wildcard | |
|---|---|---|
| Where used | Class / method declaration | Method parameter type |
| Naming | Has a name (T, E, K, V) | Anonymous (just ?) |
| Reuse in body | Yes: T item = list.get(0) | No: unknown type |
| Adding elements | Allowed (type is known) | Restricted (type unknown) |
| Typical goal | Define reusable structures | Accept flexible inputs |
How to Choose the Right Wildcard
Example 1: Counting Elements
Write a method that returns the number of null elements in any list, regardless of its type argument.
Example 2: Summing Numbers
Write a method that sums any list of numeric types: Integer, Double, Long, etc.
Example 3: Finding the Max
A method that finds the maximum element from a list of any Comparable subtype:
Read vs Write with Wildcards
Wildcard Subtyping Hierarchy
Common Mistakes
Wildcard Cheat Sheet
| Syntax | Accepts | Read As | Can Add? |
|---|---|---|---|
| <?> | Any type | Object | No |
| <? extends T> | T or subtypes | T | No |
| <? super T> | T or supertypes | Object | Yes (T) |
| <T> | Exact type | T | Yes (T) |
Question 1 of 5
Which of the following method signatures allows you to pass a List<String>, List<Integer>, or List<Dog> as an argument?
Question 2 of 5
Given a variable declared as List<? extends Number> nums, which operation is allowed?
Question 3 of 5
Why does List<Dog> NOT count as a subtype of List<Animal> in Java?
Question 4 of 5
Which statement about the unbounded wildcard <?> is false?
Question 5 of 5
You need a method that accepts a List<Integer>, List<Double>, or List<Long> and returns their sum. Which parameter type is most appropriate?