Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a primitive type (int) in as a generic type in Java?

Tags:

Specifically, with a SortedMap<Vector<String>, int> I get "dimensions expected after this (int) token." Help!

like image 291
Alexander Avatar asked Jan 05 '09 20:01

Alexander


People also ask

Can primitive types be used in generics Java?

To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.

Can we use primitive data types in generics?

Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type.

Can you substitute a generic type with a primitive data type?

The Generic types are intended for reference types, you cannot pass primitive datatypes to them if you do so a compile time error will be generated.

Can a primitive type be used as a type argument?

All reference types can be used a type arguments of a parameterized type or method. This includes classes, interfaces, enum types, nested and inner types, and array types. Only primitive types cannot be used as type argument.


1 Answers

No, this is not possible. Use Integer instead. Autoboxing takes care of the rest (i.e. for most purposes you can program as if you had actually used int because Java converts to and from Integer automatically for you).

like image 77
Konrad Rudolph Avatar answered Sep 27 '22 20:09

Konrad Rudolph