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/