Sub topic 11
Patterns and generic types
This chapter assumes you know Java generics (type parameters, wildcards, and type erasure), plain instanceof and casts, and the type pattern syntax o instanceof String s. It covers which generic types you can write in a pattern, why the compiler rejects some of them, and how to write the ones it accepts.
The old restriction
Before pattern matching, instanceof accepted only reifiable types. A reifiable type is one whose full type information exists at runtime. String, List<?>, and raw List are reifiable. List<String> is not, because erasure removes the String at compile time.
This old code did not compile:
Object o = new java.util.ArrayList<String>();
// Before Java 16: error, illegal generic type for instanceof
boolean b = o instanceof java.util.List<String>;The reason was sound. At runtime the JVM can check that o is a List. It cannot check that it is a List of String. A test that looks like it checks the element type would be misleading.
The rule since Java 16
The compiler now accepts a generic type in instanceof, with or without a pattern, if the cast it implies is checked. A checked cast is one where the compiler can prove the type arguments are correct from the static type of the expression. The runtime test still looks only at the erased class. The compiler's proof makes that test enough.
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
public class GenericPatterns {
static int size(Collection<String> c) {
if (c instanceof List<String> list) {
return list.size();
}
return 0;
}
public static void main(String[] args) {
System.out.println(size(new ArrayList<>(List.of("a", "b"))));
System.out.println(size(new HashSet<>(List.of("a"))));
}
}This prints 2, then 0.
c has the static type Collection<String>. Every List that is also a Collection<String> must be a List<String>, because List<E> extends Collection<E> with the same E. So the cast from Collection<String> to List<String> cannot put a wrong element type into list, and the compiler allows it. The binding variable list has the type List<String>, so list.get(0) returns a String with no further cast.
When the compiler refuses
A cast is unchecked when the compiler cannot prove the type arguments from the static type of the expression. The most common case is an Object tested against a parameterized type.
static int countItems(Object o) {
// Does not compile: Object cannot be safely cast to List<String>.
// if (o instanceof List<String> list) { return list.size(); }
if (o instanceof List<?> list) {
return list.size();
}
return -1;
}Nothing about an Object says what a List it holds contains. It might be a List<Integer>. If the compiler allowed List<String>, the runtime test would pass and the binding variable would claim a type the object does not have.
The fix is an unbounded wildcard. List<?> is reifiable, so the test is exact, and the binding variable list has the type List<?>. You can call size() on it. Elements read from it have the type Object.
You can still recover element types by checking each element yourself:
static int totalLength(Object o) {
if (o instanceof List<?> list) {
int total = 0;
for (Object element : list) {
if (element instanceof String s) {
total += s.length();
}
}
return total;
}
return 0;
}This is the honest pattern when you start from Object. Each element gets its own runtime test. The compiler never has to trust something it cannot see.
Cases at a glance
| Expression type | Pattern type | Result | Why |
|---|---|---|---|
| `Collection<String>` | `List<String>` | Compiles | Checked cast, type argument carried over |
| `Object` | `List<String>` | Error | Unchecked, type argument unknown |
| `Object` | `List<?>` | Compiles | Reifiable type |
| `Object` | `List` (raw) | Compiles with a warning | Reifiable but loses type safety |
| `Collection<String>` | `List<Integer>` | Error | Provably distinct type arguments |
| `List<?>` | `ArrayList<String>` | Error | Unchecked, the `?` could be anything |
| `Collection<T>` | `List<T>` | Compiles | Same type variable on both sides |
The raw form o instanceof List list is legal, but it throws away the element type and produces a raw-type warning. Prefer List<?>. It gives the same runtime test with a safer binding variable.
Type variables
Patterns work inside generic methods when the type variable appears on both sides of the cast.
import java.util.Collection;
import java.util.List;
public class FirstElement {
static <T> T firstOrNull(Collection<T> c) {
if (c instanceof List<T> list && !list.isEmpty()) {
return list.get(0);
}
return c.isEmpty() ? null : c.iterator().next();
}
public static void main(String[] args) {
System.out.println(firstOrNull(List.of("x", "y")));
System.out.println(firstOrNull(List.<String>of()));
}
}This prints x, then null.
The && is the same flow-scoping rule from earlier chapters: list is in scope in !list.isEmpty() because that side runs only after the pattern matched. The generic part is that Collection<T> to List<T> is a checked cast for any T.
Testing a bare T against a parameterized type is different. With T t, the check t instanceof List<String> l is rejected. Nothing connects T to String, so the cast is unchecked.
Wildcards in the binding type
A binding variable declared with wildcards keeps them. This matters when you read from it.
import java.util.Map;
public class MapPattern {
static String firstKeyType(Object o) {
if (o instanceof Map<?, ?> m && !m.isEmpty()) {
Object key = m.keySet().iterator().next();
return key.getClass().getSimpleName();
}
return "not a non-empty map";
}
public static void main(String[] args) {
System.out.println(firstKeyType(Map.of(1, "one")));
System.out.println(firstKeyType("text"));
}
}This prints Integer, then not a non-empty map.
Keys come out of Map<?, ?> as Object, and you cannot put anything except null into it. That is the normal behavior of wildcard types. The pattern did not add the restriction. It only declared a variable whose type happens to be a wildcard type.
Redundant patterns in newer versions
In Java 16 through 20, a pattern was an error if the expression's static type was already a subtype of the pattern type, because the test could never fail. Java 21 removed that restriction. The pattern then always matches for non-null values, and its use is legal. This matters mostly for generated or refactored code. A pattern that has become redundant no longer breaks compilation.
Decision guide
- Starting from a supertype that already carries the type arguments, such as
Collection<String>toList<String>, write the parameterized pattern. - Starting from
Objector an unrelated type, useList<?>orMap<?, ?>. Test elements individually if you need their types. - If the compiler says the cast cannot be safely made, do not silence it with a raw type or
@SuppressWarnings. Redesign the code so the static type carries the information, or test elements.
Exercise
Which of these two methods does not compile, and why? Give the smallest change that makes it compile. static int a(Collection<Integer> c) { return c instanceof Set<Integer> s ? s.size() : -1; } static int b(Object o) { return o instanceof Set<Integer> s ? s.size() : -1; }
Show answer
Method b does not compile. The static type Object says nothing about element types, so the cast to Set<Integer> is unchecked and the compiler rejects it. Method a compiles because Collection<Integer> to Set<Integer> is a checked cast. The smallest fix for b is to change the pattern to Set<?> s. The size() call still works, and the runtime test is exact.
Exercise
You have Object o that is expected to be a List<String>, and you need the total length of all the strings. Write a method that returns the total length and ignores any element that is not a String.
Show answer
static int totalLength(Object o) { int total = 0; if (o instanceof List<?> list) { for (Object element : list) { if (element instanceof String s) { total += s.length(); } } } return total; } The List<?> pattern is allowed because it is reifiable. The inner String pattern tests every element at runtime, so no unchecked cast is needed.