Sub topic 11
Patterns and Generic Types
Assume you know Java generics, inheritance, instanceof, and reference casts. This chapter focuses on when a generic type can appear in an instanceof pattern.
A type pattern still checks a runtime type and creates a binding variable:
if (value instanceof String text) {
System.out.println(text.length());
}With generic types, Java must account for type erasure. Type erasure means that Java usually removes generic type arguments at runtime. A runtime check can distinguish a List from a String, but it cannot normally distinguish a List<String> from a List<Integer>.
Reifiable and non-reifiable types
A reifiable type keeps enough information for a runtime check. String, List<?>, and the raw type List are examples. List<String> is usually non-reifiable because its type argument is erased.
This pattern is allowed:
if (value instanceof List<?> list) {
System.out.println(list.size());
}The runtime only needs to check whether value is a List. The wildcard says that the element type is unknown.
This pattern is normally rejected when value has type Object:
// Does not compile:
// if (value instanceof List<String> strings) { }The runtime cannot verify that every element in an arbitrary List is a String.
Safe generic downcasts
Java can allow a parameterized pattern when the expression already carries the same generic type information. For example, a Collection<String> can be checked to see whether it is also a List<String>:
import java.util.Collection;
import java.util.List;
public class GenericPatternDemo {
static int listSize(Collection<String> values) {
if (values instanceof List<String> list) {
return list.size();
}
return 0;
}
public static void main(String[] args) {
Collection<String> values = List.of("red", "green");
System.out.println(listSize(values));
}
}The runtime checks only whether values implements List. The compiler already knows from the declared type that the collection is intended to contain String values. The pattern does not inspect every element.
This is a checked narrowing conversion from one parameterized type to another. It is different from checking an arbitrary Object against List<String>.
| Expression type | Pattern type | Typical result |
|---|---|---|
| `Object` | `List<String>` | Rejected because the type argument cannot be checked |
| `Object` | `List<?>` | Allowed because `List<?>` is reifiable |
| `Collection<String>` | `List<String>` | Allowed as a checked narrowing conversion |
| `Collection<?>` | `List<String>` | Rejected because the element type is unknown |
The relationship can be visualized like this:
> callout note > A generic type pattern does not validate the runtime type of every element. Unsafe casts or heap pollution can still cause a later ClassCastException.
Common mistakes
Do not assume that adding a type pattern makes generic data safe. This code can still fail if a collection was created through an unsafe operation:
import java.util.ArrayList;
import java.util.List;
public class HeapPollutionDemo {
@SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
List raw = new ArrayList();
raw.add(42);
List<String> strings = raw;
for (String text : strings) {
System.out.println(text.length());
}
}
}The assignment is unsafe. A pattern such as instanceof List<?> would check only the list object, not the element contents.
Java 16 introduced pattern matching for instanceof as a standard feature. Later Java versions extend the same ideas to record patterns and pattern matching in switch.
Exercise
Which pattern should you use when an expression has type Object and you need to know whether it is a list, without claiming a specific element type?
Show answer
Use value instanceof List<?> list. It checks the runtime list type while correctly treating the element type as unknown.