Why don't Java Generics support primitive types?

后端 未结 6 832
轮回少年
轮回少年 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:53

    When creating an object, you cannot substitute a primitive type for the type parameter.As to the why of this restriction, it is a compiler implementation issue. Primitive types have their own bytecode instructions for loading and storing onto the virtual machine stack. So it is not impossible to compile primitive generics into these separate bytecode paths, but it would make the compiler complicated.

提交回复
热议问题