读书人

请看下面简短程序 为什么一运行就抛

发布时间: 2011-12-28 22:45:21 作者: rapoo

请看下面简短程序, 为什么一运行就抛错? 请指点
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();出错了
谁回答一下下。。


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


Idemo[] t = (Idemo[])castArray;
接口可以有实例吗
[解决办法]
直接定义Idemo array或者针对每个item转化
Idemo[] castArray= {new CdemoA(), new CdemoB()};
或者
//Idemo[] t = (Idemo[])castArray;
for(int i = 0; i < t.length; i++){
((Idemo)t[i]).foo();
}
[解决办法]
hh

读书人网 >J2SE开发

热点推荐