views:

309

answers:

4

Why Generics (in Java) works with the objects but not with primitive types?

For example

Gen<Integer> inum = new Gen<Integer>(100); // works fine, but  
Gen<int> inums = new Gen<int>(100); // is not allowed.   

Thanks !

+6  A: 

Generics in Java are an entirely compile-time construct - the compiler turns all generic uses into casts to the right type. This is to maintain backwards compatibility with previous JVM runtimes.

This:

List<ClassA> list = new ArrayList<ClassA>();
list.add(new ClassA());
ClassA a = list.get(0);

gets turned into (roughly):

List list = new ArrayList();
list.Add(new ClassA());
ClassA a = (ClassA)list.get(0);

So, anything that is used as generics has to be convertable to Object (in this example get(0) returns an Object), and the primitive types aren't. So they can't be used in generics.

C# is a separate matter - generics are implemented directly as part of the runtime, so primitive types can be used - the CLR generates new versions of generic classes for primitives and structs as they are used. The only disadvantage is (until .NET 4) no generic covariance or contravariance was allowed, unlike Java (see the super and extends keywords in generic definitions)

thecoop
Make it clear that this is for Java only.
ChaosPandion
In C# there is no problem with primitive types.
Danvil
@ChaosPandion: done
thecoop
Hmm.. List<int> can't be? I thought it can. In C# also
Stremlenye
@ChaosPandion : done with the changes.Restricted it to Java only.
RayAllen
So is generics in Java implemented a bit like C++ templates? Can you get code bloat?
danyal
@danyal: Nope - the same class implementation is used for all generic uses. It is all implemented using direct casts to/from the right types in the right places.
thecoop
A: 

For C# I do not see a problem here. List<int> is perfectly valid. You can use integral types in generic collections and custom generics without a problem in C#.

Danvil
+6  A: 

In Java, generics work the way that they do ... at least in part ... because they were added to the language a number of years after the language was designed. The language designers were constrained in their options for generics by having to come up with a design that was backwards compatible with the existing language and the Java class library.

Other programming languages (e.g. C++, C#, Ada) do allow primitive types to be used as parameter types for generics. But the flip side of doing this is that such languages' implementations of generics (or template types) typically entail generation of a distinct copy of the generic type for each type parameterization.

Stephen C
A: 

THe collections are defined to require a type which derives from java.lang.Object. The basetypes simply don't do that.

ZeissS