Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics - <int> to <Integer>

In the way of learning Java Generics, I got stuck at a point.
It was written "Java Generics works only with Objects and not the primitive types".

e.g

 Gen<Integer> gen=new Gen<Integer>(88);     // Works Fine ..  

But, with the primitive types like int,char etc ...

 Gen<int> gen=new Gen<int>(88) ;    // Why this results in compile time error 

I mean to say, since java generics does have the auto-boxing & unboxing feature, then why this feature cannot be applied when we declare a specific type for our class ?

I mean, why Gen<int> doesn't automatically get converted to Gen<Integer> ?

Please help me clearing this doubt.
Thanks.

like image 712
Saurabh Gokhale Avatar asked Feb 15 '11 06:02

Saurabh Gokhale


2 Answers

Autoboxing doesn't say that you can use int instead of Integer. Autoboxing automates the process of boxing and unboxing. E.g. If I need to store some primitive int to a collection, I don't need to create the wrpper object manually. Its been taken care by Java compiler. In the above example you are instantiating an generic object which is of Integer type. This generic object will still work fine with int but declaring int as a generic type is wrong. Generics allow only object references not the primitives.

like image 147
mittalpraveen Avatar answered Sep 23 '22 08:09

mittalpraveen


As you have discovered, you can't mention a primitive type as a type parameter in Java generics. Why is this the case? It is discussed at length in many places, including Java bug 4487555.

like image 43
sjr Avatar answered Sep 24 '22 08:09

sjr