[英]How can I get rid of this ClassCastException? (java)
I am trying to create an array of the generic class "DataStruct". 我正在尝试创建通用类“ DataStruct”的数组。 The code is the following:
代码如下:
public class DataArray<T> {
DataStruct<T>[] array;
int index;
public DataArray(int capacity) {
array = (DataStruct<T>[]) new Object[capacity]; // !!!
this.index = 0;
}
}
I get a java.lang.ClassCastException (Ljava.lang.Object; cannot be cast to [LArrayBased.DataStruct;) at the line marked with three exclamation marksat the end, while testing it. 在测试时,在最后带有三个感叹号的行上得到了java.lang.ClassCastException(Ljava.lang.Object;无法转换为[LArrayBased.DataStruct;)。
Can you please tell me the correct way to create it? 您能告诉我正确的创建方式吗?
Why not declare 为什么不申报
array = new DataStruct[capacity];
Object[]
can not be cast to DataStruct[]
. 无法将
Object[]
DataStruct[]
为DataStruct[]
。
Because arrays are refiable in nature that means arrays know their type at runtime so If you convert it to Object []
like below you will again run in to problems 因为数组本质上是可验证的,这意味着数组在运行时知道它们的类型,因此如果将其转换为
Object []
如下所示,您将再次遇到问题
Object[] array = new DataStruct[capacity];
array[0] = 10;//Array Store exception
So it is wise to declare it as DataStruct[capacity]
因此,将其声明为
DataStruct[capacity]
是明智的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.