Why don't Java Generics support primitive types?

Why do Generics in Java work with objects but not with primitive types?

For example

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

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 list = new ArrayList();

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)