编译没错,执行的时候报错Exception in thread "main" java.lang.NullPointerException为什么?

来源:4-9 学生选课---应用泛型管理课程 Ⅰ

慕粉3168680

2016-10-03 21:14

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)


写回答 关注

3回答

  • 殇丶善若水
    2016-10-03 21:55:14
    已采纳

    第8行:public List<Course> courses ;

    courses未初始化,默认值为null,用null调用方法就会出现NullPointerException(空指针异常),初始化对象就好了

    实时编程

    这个地方 是构造方法 写错了 构造方法应该是这个样子的 public TestGeneric(){ this.courses = new ArrayList<Course>(); } 这么改就可以

    2017-12-26 09:56:16

    共 4 条回复 >

  • 实时编程
    2017-12-26 09:55:15

     //编写构造器,在构造器中初始化courses属性

        public void testGeneric(){

        this.courses = new ArrayList<Course>();

        }

    第一错误出现在这里 这个地方 应该是个构造器。题目中这么写只是个普通方法。

    第二去掉void 也没有用  。去掉void 程序编译都通不过

    正确的写法应该是 构造器名次跟类名 完全一致  并且大小写也要完全一致

    应该是没有void 并且构造器名为 TestGeneric  这样实例化的时候就会执行构造器 了

      public  TestGeneric(){

        this.courses = new ArrayList<Course>();

        }


  • qq_愿做你半世浮台_0
    2016-10-03 22:18:35

    public void testGeneric(){

        this.courses = new ArrayList<Course>();

        }

    void返回类型为空,所以输入ID后返回就为空;应该把void去掉     


    慕粉3168...

    谢谢~~

    2016-10-05 17:16:48

    共 2 条回复 >

Java入门第三季

Java中你必须懂得常用技能,不容错过的精彩,快来加入吧

409767 学习 · 4530 问题

查看课程

相似问题