Sub topic 11
Unbounded Wildcards
In the last chapter you saw that List<Integer> is not a List<Number>, and that List<String> is not a List<Object> either. That rule keeps your lists safe. It also causes a problem. What if you want one method that works with any list, no matter what it holds?
The answer is the unbounded wildcard. A wildcard is a question mark ? written where a type argument would normally go. "Unbounded" means it has no limits attached. So List<?> means "a list of some type, but I don't know which one."
The Problem: A Method for Every List
Say you want a method that prints every item in a list. A first try might look like this:
import java.util.List;
public class PrintFirstTry {
static void printAll(List<Object> list) {
for (Object item : list) {
System.out.println(item);
}
}
public static void main(String[] args) {
List<Object> things = List.of("a", 1, 2.5);
printAll(things); // works
List<String> names = List.of("Ada", "Linus");
// printAll(names); // compile error: List<String> is not a List<Object>
}
}The method only accepts a List<Object>. Because generic types are invariant (a List<String> is not a subtype of List<Object>), you cannot pass a List<String>. You would need a separate method for every element type, which defeats the point of generics.
The Fix: `List<?>`
Change the parameter type to List<?>:
import java.util.ArrayList;
import java.util.List;
public class UnboundedDemo {
static void printAll(List<?> list) {
for (Object item : list) {
System.out.println(item);
}
}
public static void main(String[] args) {
List<String> names = List.of("Ada", "Linus");
List<Integer> numbers = List.of(3, 9, 4);
List<Double> prices = new ArrayList<>();
prices.add(1.99);
printAll(names); // Ada, Linus
printAll(numbers); // 3, 9, 4
printAll(prices); // 1.99
}
}Now one method accepts a list of strings, a list of integers, and a list of doubles. List<?> is a supertype of every List<Something>. A supertype is a more general type that a more specific type can be assigned to.
What You Can Do with `List<?>`
Inside the method, the compiler does not know the element type. It only knows the list holds something. That fact decides what you are allowed to do.
Reading: you get `Object`
Every Java object is an Object. So whatever the list holds, each item can safely be treated as an Object. That is why the loop above uses Object item.
static Object firstItem(List<?> list) {
return list.get(0); // the result type is Object
}You can call Object methods on each item, such as toString(), equals(), and hashCode(). You cannot call String methods like length(), because the item might not be a string.
Methods that don't depend on the element type
Many list methods never mention the element type. They all work on List<?>:
import java.util.ArrayList;
import java.util.List;
public class SafeOperations {
static void describe(List<?> list) {
System.out.println("Size: " + list.size());
System.out.println("Empty? " + list.isEmpty());
System.out.println("Contains null? " + list.contains(null));
}
static void wipe(List<?> list) {
list.clear(); // removing is always safe
}
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ada", "Linus"));
describe(names);
wipe(names);
System.out.println(names.size()); // 0
}
}Removing items with clear() or remove(Object) is allowed because taking something out can never put a wrong type in.
Writing: you can't add (except `null`)
Here is the big limit. You cannot add items to a List<?>:
import java.util.ArrayList;
import java.util.List;
public class NoAdding {
static void tryToAdd(List<?> list) {
// list.add("hello"); // compile error
// list.add(42); // compile error
list.add(null); // compiles: null fits every type
}
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(1, 2));
tryToAdd(numbers);
System.out.println(numbers); // [1, 2, null]
}
}Why the error? The method could be called with a List<Integer>. If adding "hello" were allowed, a string would end up inside a list of integers. The compiler cannot prove any value is safe, so it rejects them all. The one exception is null, because null can stand in for any reference type.
`List<?>` vs `List<Object>` vs Raw `List`
These three look alike but behave differently. A raw type is a generic type used with no angle brackets at all, like plain List. A later chapter covers raw types in detail.
| Type | Accepts a `List<String>`? | Can add a `String`? | Type-checked by compiler? |
|---|---|---|---|
| `List<Object>` | No | Yes | Yes |
| `List<?>` | Yes | No (only `null`) | Yes |
| `List` (raw) | Yes | Yes, with a warning | No |
List<Object> is a list that really holds any mix of objects. List<?> is a list of one specific type that you don't know. The raw List turns off checking, so it lets you break type safety. When you want "any list", choose List<?> over the raw type.
Other Places You'll See `?`
The wildcard works with any generic type, not just List. Common examples:
Collection<?>: any collection, such as a list or a set.Map<?, ?>: a map with unknown key and value types.Class<?>: a class object for some unknown class.
import java.util.Map;
public class OtherWildcards {
static void showClass(Object obj) {
Class<?> type = obj.getClass();
System.out.println(type.getSimpleName());
}
static int countEntries(Map<?, ?> map) {
return map.size();
}
public static void main(String[] args) {
showClass("hi"); // String
showClass(42); // Integer
System.out.println(countEntries(Map.of("a", 1, "b", 2))); // 2
}
}obj.getClass() returns Class<?> here because the compiler doesn't know the exact class of obj ahead of time.
Edge Case: Putting Items Back with a Helper
Sometimes you need to move items within a list of unknown type, for example to swap the first two items. You only put back what you took out, so it should be safe. But this fails:
// static void swap(List<?> list) {
// list.set(0, list.get(1)); // compile error: the compiler sees Object, not "?"
// }The fix is a private generic method, a method with its own type parameter, that gives the unknown type a name:
import java.util.ArrayList;
import java.util.List;
public class SwapDemo {
static void swapFirstTwo(List<?> list) {
swapHelper(list); // the compiler fills in T with the list's real type
}
private static <T> void swapHelper(List<T> list) {
T first = list.get(0);
list.set(0, list.get(1));
list.set(1, first);
}
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ada", "Linus", "Grace"));
swapFirstTwo(names);
System.out.println(names); // [Linus, Ada, Grace]
}
}This trick is called wildcard capture. The public method keeps the simple List<?> signature, and the helper does the typed work.
Common Mistakes
- Using
List<Object>for "any list". It rejectsList<String>. UseList<?>. - Using raw
Listfor "any list". It compiles, but you lose type checks and get warnings. - Trying to add to
List<?>. It won't compile. If you need to add, the parameter type must say what may be added. - Expecting a specific type when reading. Items come out as
Object. Casting them back is a sign you need a different signature.
Exercise
Write a static method countNonNull that takes any list and returns how many of its items are not null. It must accept both List<String> and List<Integer>.
Show answer
static int countNonNull(List<?> list) { int count = 0; for (Object item : list) { if (item != null) count++; } return count; } — List<?> accepts a list of any element type, and reading each item as Object is always safe.
Exercise
Given void process(List<?> list), which of these lines compile inside the method: (1) Object o = list.get(0); (2) list.add("x"); (3) list.clear(); (4) list.add(null); (5) String s = list.get(0);
Show answer
Lines 1, 3, and 4 compile. Reading gives an Object, clear only removes items, and null fits any type. Line 2 fails because the list might hold Integers. Line 5 fails because get returns Object, not String.
Exercise
Why can you pass a List<String> to a method taking List<?> but not to a method taking List<Object>?
Show answer
Generic types are invariant, so List<String> is not a subtype of List<Object>. List<?> means "a list of some unknown type", which makes it a supertype of every List<X>, including List<String>.