Sub topic 11
Unbounded Wildcards
Sometimes a method works the same way for a list of any element type. Printing every item and counting items are two examples. For methods like these, Java gives you the unbounded wildcard.
What `?` Means
A wildcard is a question mark (?) used in place of a type argument. List<?> means "a list of some type, but I don't know which type." You can read it as "list of unknown."
The last chapter showed that List<String> is not a List<Object>. So a method that takes List<Object> will not accept your list of strings. List<?> fixes this. It accepts a list of any element type.
A Worked Example
This program prints any list, whatever its element type:
import java.util.List;
public class UnboundedDemo {
static void printAll(List<?> list) {
for (Object item : list) {
System.out.println(item);
}
System.out.println("size = " + list.size());
}
public static void main(String[] args) {
printAll(List.of("apple", "pear"));
printAll(List.of(1, 2, 3));
}
}Output:
apple
pear
size = 2
1
2
3
size = 3Each item is read as an Object. Every Java object is an Object, so reading is always safe.
What You Cannot Do
You cannot add items to a List<?>. The one exception is null.
import java.util.ArrayList;
import java.util.List;
public class AddDemo {
static void tryToAdd(List<?> list) {
// list.add("hi"); // compile error: type is unknown
// list.add(5); // compile error: type is unknown
list.add(null); // allowed, but rarely useful
}
public static void main(String[] args) {
List<String> names = new ArrayList<>();
tryToAdd(names);
System.out.println(names); // [null]
}
}The compiler blocks add("hi") because the list might really be a List<Integer>. Adding a string to it would break type safety.
`List<?>` Compared with Other Choices
| Type | Accepts `List<String>`? | Can add a String? | Type checked? |
|---|---|---|---|
| `List<Object>` | No | Yes | Yes |
| `List<?>` | Yes | No | Yes |
| `List` (raw) | Yes | Yes | No |
The raw List also accepts anything, but the compiler stops checking types. List<?> keeps the compiler's checks. Prefer List<?>.
Exercise
You write static int count(List<?> items) { return items.size(); }. Can you call count(List.of(1.5, 2.5))? Inside count, could you write items.add(3.5);?
Show answer
Yes, the call compiles, because List<?> accepts a list of any element type, including List<Double>. No, items.add(3.5) does not compile. The compiler does not know the list's element type, so it only allows adding null.
Exercise
Why does a method with a List<Object> parameter reject a List<String> argument, while a List<?> parameter accepts it?
Show answer
Generic types are invariant, so List<String> is not a subtype of List<Object>. List<?> means a list of some unknown type, and every List<X> matches it.