Why don't java generics support primitive types?

Link address: http://cr.openjdk.java.net/~b.

this means that because JVM bytecode has different bytecodes for primitive types and reference types, the original type is not supported for compatibility.

At the other end, we have Java"s current erased implementation which produces one class for all reference instantiations and no support for primitive instantiations. (This is a homogeneous translation, and the restriction that Java"s generics can only range over reference types comes from the limitations of homogeneous translation with respect to the bytecode set of the JVM, which uses different bytecodes for operations on reference types vs primitive types.) However, erased generics in Java provide both behavioral parametricity (generic methods) and data parametricity (raw and wildcard instantiations of generic types.)
To achieve these goals, a homogeneous translation strategy was chosen, where generic type variables are erased to their bounds as they are incorporated into bytecode. This means that whether a class is generic or not, it still compiles to a single class, with the same name, and whose member signatures are the same. 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 anyone here give an example to explain in detail? thank you

Mar.03,2021

int a = 3 result: the value of variable an is 3.

The result of

String s = "hello world" : the value of s is the in-memory address of the string object on the right.

if you know Cramp CPP, then in other words, a variable of the basic type is a normal variable, and a variable of an object type is a pointer variable. It's fundamentally different.

in java, generics are just a representation, or grammatical sugar, which is underneath an Object, and Object is a pointer variable that cannot be assigned to a normal variable. (c/cPP supports pointer operation, but Java does not)

Menu