辜谷谷
2017-02-26 18:04
package gg;
public class Course {
public String id;
public String name;
public Course(String id,String name)
{
this.id=id;
this.name=name;
}
}
package gg;
import java.util.HashSet;
import java.util.Set;
public class Student {
public String id;
public String name;
public Set courses;
public void Student(String id,String name)
{
this.id=id;
this.name=name;
this.courses=new HashSet();
}
}
package gg;
import java.util.ArrayList;
import java.util.List;
public class ListTest {
public List coursestoselect;
public void Listest()
{
this.coursestoselect=new ArrayList();
}
public void testAdd()
{
Course c1=new Course("1", "数学");
coursestoselect.add(c1);
Course temp=(Course)coursestoselect.get(0);
System.out.println("添加课程:"+temp.id+","+temp.name);
}
public static void main(String[] args) {
ListTest lt=new ListTest();
lt.testAdd();
}
}
为什么编译出错啊?
Exception in thread "main" java.lang.NullPointerException
at gg.ListTest.testAdd(ListTest.java:16)
at gg.ListTest.main(ListTest.java:24)
这是什么错误啊?
原因是你没有实例化List对象coursestoselect!!!你把实例化放入方法ListTest()里面,而在main方法中你没有调用它(ListTest()方法)
public void Listest(){
this.coursestoselect=new ArrayList();
}
这句错了,应改为:
public ListTest(){
this.coursestoselect=new ArrayList():
}
public class ListTest {
public List coursestoselect;这句错了,由于是不同类型的所以要进行强制转换
改变后public List<Course>coursesToSelect;
在下面的也是如此this.coursestoselect=new ArrayList();改变后this.coursestoselect=new ArrayList<Course>();
你的public ListTest()构造函数多了个void,将void去掉就可以了
Java入门第三季
409792 学习 · 4340 问题
相似问题