為什么會拋出空指針異常?
add處報錯,拋出異常Exception in thread "main" java.lang.NullPointerException
代碼如下:
import java.util.ArrayList;
import java.util.List;
public class TestGeneric {
/**
* 帶有泛型Course的List類型屬性
*/
public List<Course> courses;
public void testGeneric() {
this.courses = new ArrayList<Course>();
}
/**
* 測試添加課程
* @param args
*/
public void testAdd() {
Course cr1 = new Course("1", "小學語文");
courses.add(cr1);
Course cr2 = new Course("2", "小學數學");
courses.add(cr2);
// courses.add("能否添加其他類型的內容?");
}
/**
* 測試循環遍歷
* @param args
*/
public void testForEach() {
for(Course cr : courses) {
System.out.println("課程-->" + cr.getId() + ":" + cr.getName());
}
}
/**
* 泛型集合可以添加泛型的子類型 的對象實例
* @param args
*/
public void testChild() {
ChildCourse ccr = new ChildCourse();
ccr.setId("3");
ccr.setName("我是子類型 的課程對象實例 ");
courses.add(ccr);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestGeneric tg = new TestGeneric();
tg.testAdd();
// tg.testForEach();
// tg.testChild();
}
}
2018-09-27
找到問題原因了,構造方法寫錯了,多了個void,而且構造器名字也寫錯,需要跟類名保持一致,即
public void testGeneric() {
this.courses = new ArrayList<Course>();
}
改為
public TestGeneric() {
this.courses = new ArrayList<Course>();
}
2018-09-27
未初始化?public List<Course> courses;
應在添加之前調用初始化 方法