为什么我不能创建泛型类型的数组?

pgs*_*rom 11 java language-design language-details

简而言之,这不会编译:

public <A> void test() {
    A[] temp = new A[]{};
}
Run Code Online (Sandbox Code Playgroud)

是因为向后兼容性问题,还是语言设计中的一些根本兼容性呢?

Mat*_*att 7

底线是表示数组的类必须知道组件类型.因此Class对象上的方法:

public Class<?> getComponentType()
Returns the Class representing the component type of an array. If this class does not represent an array class this method returns null.
Run Code Online (Sandbox Code Playgroud)

所以,当你尝试:

 A[] a = new A[0];
Run Code Online (Sandbox Code Playgroud)

在编译时,很明显我们不知道类型,因为它是一个通用参数.在运行时,由于类型擦除,我们不知道类型.因此实例化数组是不可能的.

将上述陈述视为等同于:

 A[] a = (A[])Array.newInstance(???, 0);
Run Code Online (Sandbox Code Playgroud)

由于类型擦除,我们无法在运行时获得A类.

有人问为什么不将编译器缩减为Object []或Number []或类似的东西?

这是因为根据组件类型将返回不同的类.所以:

 new Object[0].getClass() 
 new Integer[0].getClass()
Run Code Online (Sandbox Code Playgroud)

不是同一个班级.特别是类上的"getComponentType()"方法将返回不同的值.

因此,如果你将它减少到Object []而不是A [],你实际上并没有得到类型A []的东西,你得到的是Object [].Object []不能被装入Integer []并产生ClassCastException.


dvb*_*kel 5

类型擦除是您正在寻找的单词.它基本上意味着通用信息在编译时被擦除.其主要原因是向后兼容性.旧程序仍应在新的Java虚拟机上运行.