通用阵列创建编译错误从内部类 [英] Generic Array Creation Compilation Error From Inner Class
问题描述
我想使用泛型,像下面这样来实现链接的集合。
I'm trying to implement a linked collection using generics, something like the following.
public class A<E> {
private class B {
private B[] b;
private E item;
private B() {
this.b = new B[2];
}
} // end inner class B
} // end class A
一个是引用接班人/ predecessors和项目使用数组集合中的集合和B的元素或节点。
A is the collection and B an element or node in the collection with an array referencing successors/predecessors and an item.
该阵列创建是不允许的。我得到的错误是通用阵列创建
。我说得对认为它实际上是创建的数组A&LT; E&GT; .B
?
The array creation is not allowed. The error I get is generic array creation
. Am I right to think that what it's actually creating is an array of A<E>.B
?
如果没有,是什么造成的错误?
If not, what's causing the error?
如果是这样,我怎么能解决这个问题?
If so, how can I get around this?
我已经很明显忽略code一笔可观的,如果我所提供的是不够的,请让我知道。任何意见将是AP preciated。谢谢你。
I have obviously omitted a substantial amount of code, if what I've provided is not enough please let me know. Any advice would be appreciated. Thank you.
编辑1:我应该提到的是参数化类型必须在 A
等同于 B
。因此,通过&LT; E&GT;
的内部类是不可能的,因为它创建电子#2
和叶 A
与电子#1
。
EDIT 1: I should have mentioned that the parameterized type must be the same in A
as in B
. So passing <E>
to the inner class is not possible, as it creates E#2
and leaves A
with E#1
.
推荐答案
您拨打 B
继承外部类的通用的,因为它不是一成不变的。而你不能只让静态的,因为它会再需要电子
也。
You call B
inherits the generic from the outer class, as it is not static. And you can't just make it static, because it will then need E
also.
所以你的降B
阵列将确实需要一个类型,是通用的,即 A&LT; E&GT; .B
或如果您希望您的code更改为的静态的内部类, A·B&LT; E&GT;
(如果你会使用私有静态类B&LT; E&GT;
)
So your B.b
array will indeed need a type that is generic, i.e. A<E>.B
or if you'd change your code to a static inner class, A.B<E>
(if you would use private static class B<E>
).
在Java中,由于泛型实施(通过擦除)的方式,在阵列的类型不明确的。一方面,它应该是 B
,在另一方面,它应该是一个数组的数组对象
In Java, due to the way generics are implemented (by erasure), the type of the array is not well-defined. On one hand, it should be an array of B
, on the other hand, it should be an array of Object
.
最可行的办法似乎是使用对象[]
和显式转换。
如果你想增加的类型安全,你当然可以使用的ArrayList&LT; B&GT;
,其内部使用对象[]
呢!
The most workable solution seems to be to use Object[]
and cast explicitly.
If you want increased type safety, you can of course use an ArrayList<B>
, which internally uses Object[]
, too!
在你特别code, B B1,B2;
也可能是一个选项,它实际上是快(没有边界检查),并需要更少的内存(没有数组反对;没有大小的信息)
In you particular code, B b1, b2;
might also be an option which is actually faster (no bounds checking) and needs less memory (no array object; no size information).
这篇关于通用阵列创建编译错误从内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!