Why don't Java Generics support primitive types?

后端 未结 6 844
轮回少年
轮回少年 2020-11-21 07:18

Why do generics in Java work with classes but not with primitive types?

For example, this works fine:

List foo = new ArrayList

        
6条回答
  •  眼角桃花
    2020-11-21 07:55

    As per Java Documentation, generic type variables can only be instantiated with reference types, not primitive types.

    This is supposed to come in Java 10 under Project Valhalla.

    In Brian Goetz paper on State of the Specialization

    There is an excellent explanation about the reason for which generic were not supported for primitive. And, how it will be implemented in future releases of Java.

    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.)

    ...

    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.

提交回复
热议问题