package com.student; import java.util.ArrayList; import java.util.List; public class ListTest { private List coursesToSelect; public List getCoursesToSelect() { return coursesToSelect; } public void setCoursesToSelect(List coursesToSelect) { this.coursesToSelect = coursesToSelect; } public ListTest(){ this.coursesToSelect=new ArrayList(); } public void testAdd(){ Course cr1=new Course("1", "人类起源学"); coursesToSelect.add(cr1); Course temp=(Course) getCoursesToSelect();//这边输0会报错 System.out.println("输入进的课程:"+temp.getId()+"-"+temp.getName()); } public static void main(String[] args) { // TODO 自动生成的方法存根 ListTest lt=new ListTest(); lt.testAdd(); }
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.student.Course at com.student.ListTest.testAdd(ListTest.java:20) at com.student.ListTest.main(ListTest.java:26)
一开始以为你设了private属性,然后直接调用发生错误,但看代码,有用public方法返回列表,妥的;
发现,你没用get()方法来获取录入的课程信息。多打代码,注意自己和老师代码是否一致。
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.student.Course
at com.student.ListTest.testAdd(ListTest.java:20)
at com.student.ListTest.main(ListTest.java:26)
package com.student;
import java.util.ArrayList;
import java.util.List;
public class ListTest {
private List coursesToSelect;
public List getCoursesToSelect() {
return coursesToSelect;
}
public void setCoursesToSelect(List coursesToSelect) {
this.coursesToSelect = coursesToSelect;
}
public ListTest(){
this.coursesToSelect=new ArrayList();
}
public void testAdd(){
Course cr1=new Course("1", "人类起源学");
coursesToSelect.add(cr1);
Course temp=(Course) getCoursesToSelect();
System.out.println("输入进的课程:"+temp.getId()+"-"+temp.getName());
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
ListTest lt=new ListTest();
lt.testAdd();
}