铸造对象[] Java中的引用类型数组 [英] casting Object[] to a reference type array in java
问题描述
在实现一个通用的堆栈,下面的语句是用来和工作没有任何问题。
In implementation of a generic stack ,the following idiom is used and works without any problem
public class GenericStack<Item> {
private int N;
private Item[] data;
public GenericStack(int sz) {
super();
data = (Item[]) new Object[sz];
}
...
}
然而,当我尝试以下方法,它会导致一个ClassCastException
However when I try the following ,it causes a ClassCastException
String[] stra = (String[]) new Object[4];
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
你怎么解释?
推荐答案
铸造一个新的对象[4]
到的String []
不起作用,因为对象[]
不是的String []
,就像一个对象
不是字符串
。
Casting a new Object[4]
to a String[]
doesn't work because an Object[]
isn't a String[]
, just like an Object
isn't a String
.
第一个例子工程,因为类型擦除的。在运行时,类型参数项目
已擦除对象
。然而,如果你试图将数组分配给reifiable类型,它同样也会失败,例如,如果数据
不是私人
:
The first example works because of type erasure. At runtime, the type parameterItem
has been erased to Object
. However it would similarly fail if you tried to assign the array to a reifiable type, for example if data
wasn't private
:
String[] strings = new GenericStack<String>(42).data;
这同样也会抛出一个 ClassCastException异常
,因为究竟是怎样一个对象[]
将转换为的String []
。
This would similarly throw a ClassCastException
, because what is actually an Object[]
would be cast to String[]
.
这篇关于铸造对象[] Java中的引用类型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!