Course contentsShow
← Java
Lesson 958 of 2,87022. Generics: Bounds and WildcardsFree lesson

Cannot Instantiate Generic Types with Primitives

Understand why List<int> is invalid and must use List<Integer>, due to type erasure and primitives not being reference types.

Cannot Instantiate Generic Types with Primitives

What you'll learn: Why you must use wrapper classes like Integer instead of primitives like int when working with Java generics.

The Core Problem

Java generics work exclusively with reference types, not primitive types. This means you cannot write List<int> or ArrayList<double>. Instead, you must use their wrapper class equivalents: List<Integer> and ArrayList<Double>.

Why This Restriction Exists

Remember that type erasure removes all generic type information at runtime, replacing type parameters with Object (or their bound). Primitives like int, char, and boolean are not objects—they're fundamental values stored directly in memory, not references pointing to objects on the heap.

Since generics expect reference types that can be treated as Object after erasure, primitives simply don't fit. There's no way to treat an int as an Object without boxing it into an Integer first.

The Solution: Wrapper Classes

Java provides wrapper classes for all eight primitive types:

  • int → Integer
  • double → Double
  • boolean → Boolean
  • char → Character
  • long → Long
  • float → Float
  • byte → Byte
  • short → Short

Thanks to autoboxing (which you've already learned), using wrapper classes feels almost seamless:

// INVALID - compiler error
// List<int> numbers = new ArrayList<int>();

// VALID - uses wrapper class
List<Integer> numbers = new ArrayList<>();
numbers.add(42);  // autoboxing converts int to Integer
int value = numbers.get(0);  // auto-unboxing converts back

Key Takeaway: Generic types require reference types, so primitives must be wrapped in their corresponding wrapper classes (e.g., Integer for int) due to type erasure and the fundamental difference between primitives and objects.