关于数组的转型:
Class SHA{ public void print(){ ...} }
Class SHB extends SHA { public void print() { ...} }
对于代码:
Object[] oa = new Object[] { new Integer(1), new Integer(2), new Integer(3) };
System.out.println(oa[0].getClass());
Integer[] ia = (Integer[]) oa;
int i;
for (i = 0; i < ia.length; i++)
System.out.println(ia[i]);
SHA[] sha = new SHB[]{new SHB(), new SHB()};
SHB[] shb = (SHB[])sha;
for (i = 0; i < shb.length; i++)
System.out.println(shb[i]);
第一段在“Integer[] ia = (Integer[]) oa;” 出错:[Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
但是第二段代码 “SHB[] shb = (SHB[])sha;”没有问题
两者都是基类(基基类)、派生类的关系,那么为什么会出现这种状况? |