java - 泛型类实例的三种声明之间的区别

标签 java arrays generics

Gen <Integer> iOb = new Gen <> (50, n);    //Works good

Gen <Integer> gens[] = new Gen <> [10];    //Error

Gen <?> gen[] = new Gen <?> [10];          //Alternative way for the second form

我想知道为什么第一个和第三个声明可以正常工作,但第二个声明却不能。

三者有什么区别?

最佳答案

第二行和第三行是创建通用数组的示例。第二个是不可具体化的。这意味着该类型在运行时不可用。

JLS, Section 15.10 ,涵盖数组创建:

It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7).

Section 4.7定义一个可具体化的类型:

A type is reifiable if and only if one of the following holds:

  • It refers to a non-generic class or interface type declaration.

  • It is a parameterized type in which all type arguments are unbounded wildcards (§4.5.1).

  • It is a raw type (§4.8).

  • It is a primitive type (§4.2).

  • It is an array type (§10.1) whose element type is reifiable.

  • It is a nested type where, for each type T separated by a ".", T itself is reifiable.

因此,第二行是不允许的,因为它是不可具体化的类型的数组类型,因为它是通用的并且不全是无界通配符。第三行很好,只是因为它的泛型都是无界通配符。

第一行没问题,因为它不是数组。

关于java - 泛型类实例的三种声明之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190561/

相关文章:

c# - 使用泛型乘以整数

java - 忽略警告 :unchecked conversion in java 的后果是什么

algorithm - 通用排序函数接受 T,但要确保 T 是可比较的

java - 在 Spring MVC 中组合 @ModelAttribute 和 @RequestBody 的功能

java - 理解 Guava 的 TypeToken.isAssignableFrom 方法

java - 由于基础异常 : Connection Time Out 导致通信链接失败

java - 如何在 Java 中将文件读取为无符号字节?

c++ - 如何对类数组进行排序

c++ - 围绕现有数组的 STL 非复制包装器?

arrays - Bash 扩展通配括号破坏数组初始化