package com.imooc.collection;
import java.util.List;
import java.util.ArrayList;;
//测试泛型
public class TestGeneric {
//带有泛型Course的list
public List<Course> courses ;
//编写构造器,在构造器中初始化courses属性
public void testGeneric(){
this.courses = new ArrayList<Course>();
}
/**
* 测试添加
* @param args
*/
public void testAdd(){
Course cr1 = new Course("1","大学英语");
courses.add(cr1);
//在泛型集合中,不能添加规定类型以外的类型,否则会报错
//courses.add("在list中尝试添加字符串。");
Course cr2 = new Course ("2","大学数学");
courses.add(cr2);
}
/**
* 测试循环遍历
* @param args
*/
public void testForEach(){
System.out.println("有如下课程待选(通过foreach语句)");
//courses中存的对象是Course,这里不用先取出object类型对象再转换(泛型好处)
for(Course cr : courses){
System.out.println(cr.id+cr.name);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestGeneric tg = new TestGeneric();
tg.testAdd();
tg.testForEach();
}
}
报错:
Exception in thread "main" java.lang.NullPointerException
at com.imooc.collection.TestGeneric.testAdd(TestGeneric.java:21)
at com.imooc.collection.TestGeneric.main(TestGeneric.java:43)