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)
第8行:public List<Course> courses ;
courses未初始化,默认值为null,用null调用方法就会出现NullPointerException(空指针异常),初始化对象就好了
//编写构造器,在构造器中初始化courses属性
public void testGeneric(){
this.courses = new ArrayList<Course>();
}
第一错误出现在这里 这个地方 应该是个构造器。题目中这么写只是个普通方法。
第二去掉void 也没有用 。去掉void 程序编译都通不过
正确的写法应该是 构造器名次跟类名 完全一致 并且大小写也要完全一致
应该是没有void 并且构造器名为 TestGeneric 这样实例化的时候就会执行构造器 了
public TestGeneric(){
this.courses = new ArrayList<Course>();
}
public void testGeneric(){
this.courses = new ArrayList<Course>();
}
void返回类型为空,所以输入ID后返回就为空;应该把void去掉