Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not auto-box Java primitive types for Generics?

Java does not allow primitive types to be used in generic data structures. E.g. ArrayList<int> is not allowed. The reason is, primitive types can not be directly converted to Object. However Java 1.5 does support auto-boxing, and wrapper classes work in generic data structures. So why couldn't the compiler auto-box it to ArrayList<Integer>? Are there any other reasons for why this can not work?

like image 338
shrini1000 Avatar asked Aug 12 '11 06:08

shrini1000


People also ask

Why don t Java generics support primitive types?

Type safety is verified at compile time, and runtime is unfettered by the generic type system. In turn, this imposed the restriction that generics could only work over reference types, since Object is the most general type available, and it does not extend to primitive types.

Can generics be used for primitive types?

Note: It is not possible to use primitive types with generics; only reference types can be used. Autoboxing and unboxing make it possible to store and retrieve values to and from primitive types when working with generic objects.

Why Java collections Cannot directly store primitives types?

Since java is a Statically typed language where each variable and expression type is already known at compile-time, thus you can not define a new operation for such primitive types.


2 Answers

So as far as I understand it, your proposed ArrayList<int> would be identical to ArrayList<Integer>. Is that right? (In other words, internally it still stores an Integer; and every time you put something in or get it out, it would automatically box/unbox it, but autoboxing/autounboxing already does that for ArrayList<Integer>.)

If it is the same, then I don't understand what the utility of having a duplicate syntax <int> is when it means the same thing as <Integer>. (In fact it will introduce additional problems, because for example int[] is not the same runtime type as Integer[], so if you have T[], and T is int, what would it mean?)

like image 87
newacct Avatar answered Oct 12 '22 01:10

newacct


The generic type information is erased at run time. Check this link. Generics have more to do with compile time checking than run time checking. The autoboxing and unboxing are the run time operations. See the link. This is the reason that autoboxing should not work with Generics.

like image 21
Santosh Avatar answered Oct 12 '22 03:10

Santosh