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;
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;
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();
}
}
}
这样就可以了
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];
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[] castArray= {new CdemoA(), new CdemoB()};
或者
//Idemo[] t = (Idemo[])castArray;
for(int i = 0; i < t.length; i++){
((Idemo)t[i]).foo();
}
Idemo[] t = (Idemo[])castArray;
for(int i = 0; i < t.length; i++){
t[i].foo();
这样的调用,到底为什么不行,还没有明确的解释。