package imooc_collection_lesson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SetTest {
private static final List<Course> coursesToSelect = null;
public List<Course> coursesToCourses;
public SetTest(){
coursesToCourses=new ArrayList<Course>();
}
public void TestAdd(){
//创建一个课程对象,并通过add方法,添加到备选课程中去
Course cou1=new Course("1","数据结构");
coursesToCourses.add(cou1);
Course Temp=(Course)coursesToCourses.get(0);
//System.out.println("添加了一个课程:"+Temp.id+":"+Temp.name);
Course cou2=new Course("2", "C语言");
coursesToCourses.add(0,cou2);
Course Temp2=(Course)coursesToCourses.get(0);
//System.out.println("添加了一个课程:"+Temp2.id+":"+Temp2.name);
//以下方法会抛出数组下标越界异常
/* Course cou3=new Course("3", "大学英语");
courseToSelect.add(4,cou3);
*/
//Course cou3=new Course("1", "数据结构");
//courseToSelect.add(2,cou3);
Course[] course={new Course("3","离散数学"),
new Course("4","汇编语言")};
coursesToCourses.addAll(Arrays.asList(course));
Course Temp3=(Course) coursesToCourses.get(2);
Course Temp4=(Course) coursesToCourses.get(3);
//System.out.println("添加了两门课程:"+Temp3.id+":"+Temp3.name
// +Temp4.id+":"+Temp4.name);
Course[] course2={new Course("5","高等数学"),
new Course("6","大学体育")};
coursesToCourses.addAll(2,Arrays.asList(course2));
Course Temp5=(Course) coursesToCourses.get(2);
Course Temp6=(Course) coursesToCourses.get(3);
//System.out.println("添加了两门课程:"+Temp5.id+":"+Temp5.name
// +Temp6.id+":"+Temp6.name);
}
public void testForEach(){
System.out.println("有如下课程待选(通过for each访问):");
for(Object obj:coursesToCourses){
Course sr=(Course) obj;
System.out.println("课程:"+sr.id+";"+sr.name);
}
}
/**
* 测试List的contains方法
*/
public void testListContains() {
// 取得备选课程序列的第0个元素
Course course = coursesToSelect.get(0);
// 打印输出coursesToSelected是否包含course对象
System.out.println("取得课程:" + course.name);
System.out.println("备选课程中是否包含课程:" + course.name + ", " +
coursesToSelect.contains(course));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SetTest st=new SetTest();
st.TestAdd();
st.testListContains();
}
public void testForEachForSet(Student student)
{
for (Course sr : student.Courses) {
System.out.println("选择了课程:"+sr.id+":"+sr.name);
}
}
}
执行时报错Exception in thread "main" java.lang.NullPointerException at imooc_collection_lesson.SetTest.testListContains(SetTest.java:67) at imooc_collection_lesson.SetTest.main(SetTest.java:77)
coursesToSelect这个字段为空哦,所以报了Null 指针异常,而且定义为static final的话就永远等于空啦
可以改成
private static List<Course> coursesToSelect = new ArrayList<Course>();