Restrictions: Cannot Instantiate Type Parameters with new T()
You'll learn why you cannot create instances of generic type parameters directly and how to work around this limitation.
The Problem
When writing generic classes, you might want to create a new instance of the type parameter inside your class. Unfortunately, this doesn't work:
public class Container<T> {
private T item;
public Container() {
// ILLEGAL! Will not compile
item = new T();
}
}
Why This Fails: Type Erasure
At runtime, Java "erases" all generic type information. Your Container<String> and Container<Integer> both become just plain Container in the compiled bytecode. The JVM has no idea what T actually is when it tries to execute new T()—it could be String, Integer, or any class. Since the JVM doesn't know which constructor to call or how much memory to allocate, it can't create the object.
Analogy: Imagine someone hands you a shopping list that just says "buy one." One what? Apples? Cars? You can't fulfill that request without knowing the specific type.
Common Workarounds
Since new T() is forbidden, you typically pass the necessary information to create instances:
Pass an instance directly:
public Container(T item) {
this.item = item; // Caller provides the object
}
Pass a Class object (advanced, uses reflection—not yet covered in detail):
// Uses Class<T> parameter (reflection-based approach)
Key Takeaway: You cannot use new T() because type erasure removes generic type information at runtime, leaving the JVM unable to instantiate the unknown type. Work around this by having callers provide instances or using factory patterns.