Generics and Primitive Data Types - RichardDanielOliva/java-learning-wiki GitHub Wiki

A restriction of generics in Java is that the type parameter cannot be a primitive type.

For example, the following doesn't compile:

List<int> list = new ArrayList<>();
list.add(17);

To understand why primitive data types don't work, let's remember that generics are a compile-time feature, meaning the type parameter is erased and all generic types are implemented as type Object.

As an example, let's look at the add method of a list:

List<Integer> list = new ArrayList<>();
list.add(17);

Therefore, type parameters must be convertible to Object. Since primitive types don't extend Object, we can't use them as type parameters.

However, Java provides boxed types for primitives, along with autoboxing and unboxing to unwrap them:

Integer a = 17;
int b = a;

So, if we want to create a list which can hold integers, we can use the wrapper:

List<Integer> list = new ArrayList<>();
list.add(17);
int first = list.get(0);

The compiled code will be the equivalent of:

List list = new ArrayList<>();
list.add(Integer.valueOf(17));
int first = ((Integer) list.get(0)).intValue();

Future versions of Java might allow primitive data types for generics. Project Valhalla aims at improving the way generics are handled. The idea is to implement generics specialization as described in JEP 218.

References:

⚠️ **GitHub.com Fallback** ⚠️