I tried in my code to use a primitive type as an argument to a list.
List<int> list = ... //int n’est pas un sous-type d’objet
But it seems that it is illegal et that it is necessary to use an Object
List<Integer> list = ...
Why is it not possible to use a primitive type as an argument?
Generic classes cannot be parameterized to primitive types. To solve this problem, the language defines wrapper classes of the primitive types:
Integer
,Float
,Double
,Character
,Boolean
, etc.The compiler automatically transforms primitive types into wrapper classes and vice versa:
What you are trying to do is not possible because in Java, the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend from
Object
, they cannot be used as generic type arguments to a parameterized type.That's why with
Integer
works, because it does extend fromObject
, while itint
is primitive.And, since Java 7 you can do this:
However it should be noted that with autoboxing in Java , the primitive type
int
will be converted to aInteger
when needed.Autoboxing is the automatic conversion that the Java compiler performs between primitive types and their corresponding object wrapper classes.
So this is valid:
You can use arrayList for that purpose as follows:
You cannot declare a List as an array, for example:
You must do it as follows:
Generic classes in java expect an object to extend from
Object
, primitive data types such asint, long, char
, etc, do not extend from it.Integer
is a wrapper of the primitive typeint
An object is a different thing than a primitive type, even though they contain the same information. Always keep in mind that objects in Java ( Integer ) have one treatment type and primitive types ( int ), another. That at a given moment they contain the same information does not mean in any case that they are the same.
Here a read about the difference between Primitive Data Types and Classes