Sub topic 16
What You Cannot Do with Generics
Generics catch many mistakes before your program runs. They also come with rules that can surprise you. Some code that looks reasonable will not compile. This chapter lists those rules, explains why each one exists, and shows a working alternative for each.
Most of these rules come from type erasure. Type erasure is the step where the compiler removes type arguments after it has checked your code. You met it in the previous chapter. After erasure, a List<String> and a List<Integer> both run as a plain ArrayList. The running program does not know what T was. Keep that in mind as you read. Most of the rules follow from it.
The Rules at a Glance
| You cannot... | Example that fails | Why | What to do instead |
|---|---|---|---|
| Use a primitive as a type argument | `List<int>` | Type arguments must be objects | Use a wrapper class: `List<Integer>` |
| Create an object of type `T` | `new T()` | `T` is unknown at runtime | Pass in a `Supplier<T>` |
| Create an array of `T` | `new T[10]` | Arrays must know their element type at runtime | Use `List<T>`, or pass a `Class<T>` |
| Declare a static field of type `T` | `static T shared;` | Static fields are shared by every `Box<...>` | Use an instance field |
| Check a generic type with `instanceof` | `obj instanceof List<String>` | The type argument is gone at runtime | Check `List<?>`, then check the elements |
| Overload methods that erase to the same signature | `print(List<String>)` and `print(List<Integer>)` | Both become `print(List)` | Give the methods different names |
| Make a generic exception class | `class MyEx<T> extends Exception` | `catch` runs at runtime and needs a real type | Store extra data in a normal field |
The sections below explain each rule.
No Primitive Type Arguments
A primitive type is one of Java's built-in value types, such as int, double, or boolean. A type parameter can only stand for a reference type. A reference type is a class or interface type, such as String or Integer.
import java.util.ArrayList;
import java.util.List;
public class PrimitiveDemo {
public static void main(String[] args) {
// List<int> numbers = new ArrayList<>(); // compile error
List<Integer> numbers = new ArrayList<>(); // works
numbers.add(5); // the int 5 is boxed to an Integer
int first = numbers.get(0); // the Integer is unboxed back to an int
System.out.println(first + 1); // 6
}
}Java converts between int and Integer for you. Turning int into Integer is called autoboxing. The reverse is called unboxing. So in practice you write Integer in the angle brackets and can still use plain numbers in your code.
No `new T()`
You might want a generic class to build its own objects. That does not compile.
public class Factory<T> {
// T make() { return new T(); } // compile error
}To run new, the JVM needs to know the exact class. After erasure, T is just Object. It could even be an interface or an abstract class, and neither of those can be created with new.
The fix is to let the caller tell you how to build a T. A Supplier<T> is a small built-in interface whose get() method returns a new value. You can pass a constructor reference such as StringBuilder::new as a supplier.
No Generic Arrays
An array always remembers its element type at runtime. That memory is how Java can throw an ArrayStoreException when you put the wrong object into an array. A T[] cannot remember a type that erasure has removed, so new T[10] is not allowed. For a related reason, new List<String>[10] is not allowed either.
The simplest fix is to use a List<T> instead of an array. If you really need an array, you can pass in a Class<T> object. A Class<T> object describes a real class at runtime, so Java can use it to build the array.
No Static Fields of Type `T`
A static field belongs to the class itself, not to any one object. Only one copy exists. Suppose this were allowed:
public class Box<T> {
// static T shared; // compile error
}Box<String> and Box<Integer> share the same class, and so they would share the same field. One part of your code would treat shared as a String, another part would treat it as an Integer, and something would break. The compiler blocks this. Static methods can still be generic, but they must declare their own type parameter, such as static <U> U pick(U a).
Limited `instanceof` Checks
instanceof runs while the program is running. By then, the type argument is gone, so the check obj instanceof List<String> cannot be answered when obj is an Object. You can check for List<?> instead. The ? means "a list of some unknown type". Then you check each element yourself.
Putting the Workarounds Together
This program runs as shown. It uses a supplier instead of new T(), a Class<T> to build an array, and List<?> for an instanceof check.
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class Workarounds {
// Instead of new T(): ask the caller for a Supplier
static <T> List<T> makeMany(Supplier<T> factory, int count) {
List<T> result = new ArrayList<>();
for (int i = 0; i < count; i++) {
result.add(factory.get());
}
return result;
}
// Instead of new T[size]: use a Class<T> object
@SuppressWarnings("unchecked")
static <T> T[] makeArray(Class<T> type, int size) {
return (T[]) Array.newInstance(type, size);
}
// Instead of obj instanceof List<String>: check List<?>, then the elements
static boolean isListOfStrings(Object obj) {
if (!(obj instanceof List<?> list)) {
return false;
}
for (Object item : list) {
if (!(item instanceof String)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
List<StringBuilder> builders = makeMany(StringBuilder::new, 3);
System.out.println(builders.size()); // 3
String[] names = makeArray(String.class, 2);
names[0] = "Ada";
names[1] = "Linus";
System.out.println(names.length + " " + names[0]); // 2 Ada
System.out.println(isListOfStrings(List.of("a", "b"))); // true
System.out.println(isListOfStrings(List.of(1, 2))); // false
}
}The @SuppressWarnings("unchecked") line tells the compiler you know the cast to T[] is safe here. It is safe because Array.newInstance really builds an array of the class you passed in. Use this annotation only when you can explain why the cast is correct.
instanceof List<?> list uses a pattern variable. A pattern variable is a name that is set when the check passes. This feature needs Java 16 or later.
Methods That Clash After Erasure
Two methods with the same name usually work if their parameter types differ. With generics, the compiler compares the types after erasure.
import java.util.List;
public class Printer {
void printStrings(List<String> items) { System.out.println(items); }
void printNumbers(List<Integer> items) { System.out.println(items); }
// void print(List<String> items) {}
// void print(List<Integer> items) {} // compile error: name clash, same erasure
}Both commented methods would become print(List), so the JVM could not tell them apart. Use different names.
No Generic Exceptions
A class that extends Throwable cannot have type parameters. A catch (MyException<String> e) block would need to check the type argument at runtime, which erasure makes impossible. If an exception needs to carry extra data, store that data in a normal field of type Object or of a specific type.
Deciding on a Workaround
Summary
- Type arguments must be reference types. Use
Integer, notint. - You cannot write
new T()ornew T[n], becauseTdoes not exist at runtime. Pass aSupplier<T>or aClass<T>instead. - Static fields cannot use the class's
T, because every version of the class shares them. instanceofcannot check a type argument on a plainObject. CheckList<?>and then check the elements.- Methods that erase to the same signature clash, and exception classes cannot be generic.
Exercise
A classmate writes class Stack<T> { private T[] items = new T[100]; } and gets a compile error. Explain why, and give two ways to fix it.
Show answer
Arrays must know their element type at runtime, but erasure removes T, so new T[100] is not allowed. Fix 1: use a List<T> items = new ArrayList<>(); instead of an array. Fix 2: add a constructor that takes a Class<T> type and build the array with (T[]) java.lang.reflect.Array.newInstance(type, 100), marking the cast with @SuppressWarnings("unchecked").
Exercise
Which of these lines compile? (a) List<double> xs; (b) List<Double> xs; (c) static T cache; inside class Cache<T> (d) static <U> U id(U u) { return u; } inside class Cache<T>.
Show answer
Only (b) and (d) compile. (a) fails because primitives cannot be type arguments. (c) fails because a static field cannot use the class's type parameter. (d) works because the static method declares its own type parameter U.
Exercise
Why does a class with both void save(List<String> a) and void save(List<Integer> b) fail to compile?
Show answer
After type erasure, both methods have the signature save(List). The JVM cannot tell them apart, so the compiler reports a name clash. Rename one of them, for example to saveNames and saveIds.