为什么 Java 泛型不支持原始类型?

为什么 Java 泛型不支持原始类型?

问题描述:

为什么 Java 中的泛型适用于类而不适用于原始类型?

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

例如,这很好用:

List<Integer> foo = new ArrayList<Integer>();

但这是不允许的:

List<int> bar = new ArrayList<int>();

Java 中的泛型完全是编译时构造 - 编译器将所有泛型用途转换为正确类型的强制转换.这是为了保持与以前的 JVM 运行时的向后兼容性.

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.

这个:

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

变成(大致):

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

因此,任何用作泛型的东西都必须可以转换为 Object(在这个例子中 get(0) 返回一个 Object),并且原始类型是'吨.所以它们不能用在泛型中.

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.