Sub topic 16
What You Cannot Do with Generics
The last chapter showed that Java erases type arguments when it compiles your code. Type erasure is the step where the compiler checks your types and then removes them. At runtime, a List<String> is just a List. Because of this, some things that look reasonable will not compile. This chapter covers each of these rules and shows what to write instead.
The Rules at a Glance
| You cannot write | Why not | What to do instead |
|---|---|---|
| `List<int>` | Type arguments must be objects, not primitives | Use a wrapper class: `List<Integer>` |
| `new T()` | At runtime, Java does not know what `T` is | Pass in a `Supplier<T>` |
| `new T[10]` | An array must know its element type at runtime | Use a `List<T>` |
| `static T shared;` | Static fields are shared by all `Box<String>`, `Box<Integer>`, and so on | Use a normal instance field |
| `obj instanceof List<String>` | The `<String>` part is gone at runtime | Check `obj instanceof List<?>` |
A primitive is one of Java's basic value types, such as int, double, or boolean. A wrapper class is the object version of a primitive. Integer wraps int, and Double wraps double.
Seeing the Errors
Each commented line below is a compile error. Remove the // from any one of them to see the message.
import java.util.ArrayList;
import java.util.List;
public class Restrictions<T> {
// T value = new T(); // error: cannot instantiate a type parameter
// T[] items = new T[10]; // error: generic array creation
// static T shared; // error: static field cannot use T
// List<int> numbers; // error: primitives not allowed
private final List<T> items = new ArrayList<>(); // this works
}The Workarounds in Action
This program uses each fix. A Supplier<T> is a built-in interface with one method, get(), that returns a new object. You pass it in, and it does the creating that new T() cannot do.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class Workarounds {
static <T> T create(Supplier<T> maker) {
return maker.get();
}
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(7); // the int 7 is boxed into an Integer
StringBuilder sb = create(StringBuilder::new);
sb.append("made by a Supplier");
Object obj = numbers;
if (obj instanceof List<?>) {
System.out.println("obj is some kind of List");
}
System.out.println(numbers + " " + sb);
}
}Output:
obj is some kind of List
[7] made by a SupplierAutoboxing is Java turning a primitive into its wrapper object for you. That is why numbers.add(7) works without you writing Integer.valueOf(7).
Exercise
Why does List<double> prices = new ArrayList<>(); fail to compile, and how do you fix it?
Show answer
Type arguments must be object types, and double is a primitive. Use the wrapper class instead: List<Double> prices = new ArrayList<>();. Autoboxing converts each double you add into a Double.
Exercise
A method needs to return a new object of type T, but new T() will not compile. What can you pass to the method so it can still create the object?
Show answer
Pass a Supplier<T>, such as ArrayList::new, and call get() on it inside the method. The caller knows the real type, so the caller supplies the way to build it.