Type Arguments Cannot Be Primitives
You'll learn why generics require reference types and how Java automatically handles primitives in generic contexts.
The Core Rule
When you create an instance of a generic class, you cannot use primitive types like int, double, or boolean as type arguments. Generics in Java only accept reference types (classes and interfaces).
// This does NOT compile
List<int> numbers = new List<>(); // ERROR!
// This works
List<Integer> numbers = new List<>(); // OK
Why This Restriction Exists
Generics were added to Java after the language was already mature. To maintain backward compatibility, generic type information is erased at runtime (more on this later in your journey). The JVM treats all generic types as Object, but primitives like int aren't objects—they're basic values stored directly in memory. They can't be treated as Object, so they can't be type arguments.
Autoboxing to the Rescue
Java bridges this gap with autoboxing: the automatic conversion between primitives and their wrapper classes (int ↔ Integer, double ↔ Double, etc.).
List<Integer> scores = new ArrayList<>();
scores.add(95); // autoboxing: int → Integer
int first = scores.get(0); // unboxing: Integer → int
You write code as if you're using primitives, but Java quietly wraps and unwraps them as needed.
Analogy
Think of generics as a club that only admits "boxed gifts" (objects). Primitives are like loose coins—they need to be put in a gift box (wrapper class) before entry. Autoboxing is the attendant who boxes your coins automatically.
Key Takeaway:
Primitives cannot be type arguments in generics; use their wrapper classes (Integer, Double, etc.) instead, and rely on autoboxing for seamless conversion.