package course;
public class Course {
public String id;
public String name;
public Course(String id,String name)
{
this.id=id;
this.name=name;
}
}
package course;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
//选课类就是一个List容器
public class ChooseCourse {
public List choose;
public ChooseCourse()
{
this.choose=new ArrayList();
}
public void add()
{
Course cr=new Course("1.","数据库");
Course[]cr2={new Course("2.","操作系统"),new Course("3.","计算机网络")};
choose.add(cr);
choose.add(1, cr2);
Course cr3=(Course) choose.get(0);
System.out.println("添加了课程"+cr3.id+cr3.name);
}
public void iterator()
{
Iterator it=choose.iterator();
while(it.hasNext())
{
Course cr=(Course) it.next();
System.out.println("课程号:"+cr.id+"课程名:"+cr.name);
}
}
public static void main(String[] args) {
ChooseCourse cc=new ChooseCourse();
cc.add();
cc.iterator();
// TODO 自动生成的方法存根
}
}
错误信息xception in thread "main" java.lang.ClassCastException: [Lcourse.Course; cannot be cast to course.Course。。
请问哪里错了
public void add() { Course cr=new Course("1.","数据库"); Course[]cr2={new Course("2.","操作系统"),new Course("3.","计算机网络")}; choose.add(cr); choose.add(1, cr2); Course cr3=(Course) choose.get(0); System.out.println("添加了课程"+cr3.id+cr3.name); }
这里有问题。cr是个course对象,cr2是个course数组对象,所以在list容器中你存放了两个不同类型的对象。在后面cr2当然不能强转为course对象。应该改为:
public void add() { Course cr=new Course("1.","数据库"); Course[]cr2={new Course("2.","操作系统"),new Course("3.","计算机网络")}; choose.add(cr); choose.addAll(1, cr2.asList()); Course cr3=(Course) choose.get(0); System.out.println("添加了课程"+cr3.id+cr3.name); }
楼上正解。你可以用泛型,这样一开始编译你在添加的时候不同类型就通不过