日期:2014-05-20  浏览次数:20885 次

请看下面简短程序, 为什么一运行就抛错? 请指点
package   test;

interface   Idemo{
void   foo();
}

class   CdemoA   implements   Idemo{
public   void   foo(){}
}

class   CdemoB   implements   Idemo{
public   void   foo(){}
}

public   class   InterfaceArrayCast   {

public   static   void   main(String[]   args){
Object[]   castArray=   {new   CdemoA(),   new   CdemoB()};

Idemo[]   t   =   (Idemo[])castArray;  
for(int   i   =   0;   i   <   t.length;   i++){
t[i].foo();
}
}
}

运行时,抛出以下错误:
Exception   in   thread   "main "   java.lang.ClassCastException:   [Ljava.lang.Object;   cannot   be   cast   to   [Ltest.Idemo;
at   test.InterfaceArrayCast.main(InterfaceArrayCast.java:20)

也就是在以下这行
Idemo[]   t   =   (Idemo[])castArray;


------解决方案--------------------
interface Idemo{
void foo();
}

class CdemoA implements Idemo{
public void foo(){}
}

class CdemoB implements Idemo{
public void foo(){}
}

public class InterfaceArrayCast {

public static void main(String[] args){
Idemo[] castArray= {new CdemoA(), new CdemoB()};

//Idemo[] t = (Idemo[])castArray;
for(int i = 0; i < castArray.length; i++){
castArray[i].foo();
}
}
}
这样就可以了

------解决方案--------------------
import java.util.Iterator;

interface Idemo{
void foo();
}

class CdemoA implements Idemo{
public void foo(){}
}

class CdemoB implements Idemo{
public void foo(){}
}

public class InterfaceArrayCast {

public static void main(String[] args){
Object[] castArray= {new CdemoA(), new CdemoB()};

Idemo[] t = new Idemo[2] ;
for(int i = 0; i < castArray.length; i++){

t[i]=(Idemo)castArray[i];
t[i].foo();
}

}
}
数组好像不能直接这样赋值Idemo[] t = (Idemo[])castArray;
要分别对数组的每个对象进行赋值:t[i]=(Idemo)castArray[i];
------解决方案--------------------

直接定义成泛型可以省得你转换了
------解决方案--------------------
错误信息里写的很清楚,Object类型的数据无法转换成Idemo类型
------解决方案--------------------
package test;
import java.util.ArrayList;

interface Idemo{
void foo();
}

class CdemoA implements Idemo{
public void foo(){}
}

class CdemoB implements Idemo{
public void foo(){}
}

public class leilei {

public static void main(String[] args){
ArrayList <Idemo> castArray=new ArrayList <Idemo> ();

castArray.add(new CdemoA());
castArray.add(new CdemoB());

Idemo[] shuzu=new Idemo[castArray.size()];

for (int i=0;i <castArray.size();i++)
{
shuzu[i]=castArray.get(i);
}

}
}

用泛型怎么直接赋值啊 我只会一个一个赋值
用Idemo[] shuzu=castArray.toArray();出错了
谁回答一下下。。


------解决方案--------------------