为什么这个for循环给我一个空指针异常?

时间:2013-11-23 18:48:18

标签: java for-loop nullpointerexception

这段代码给了我一个NullPointerException。其目的是遍历ArrayList并返回与参数age。匹配的所有记录。

private String searchAge(int age) {

    for(int i = 0; i < list.size(); i++) {    //<--- ERROR ON THIS LINE
        if(list.get(i).getAge() == age) {
            System.out.println(list.get(i));
            return list.get(i).toString();
        }
    }

    return "No Records Found!";
}

我的构造函数:

public Frame() {
    Objects a = new Objects();
    list = a.getList();
}

和其他班级:

package objects;

import java.util.ArrayList;

public class Objects {


    public ArrayList<Student> list;

    public static void main(String[] args) {
        Objects a = new Objects();
        a.addStudents();
        Frame f = new Frame();
        f.setVisible(true);

    }

    public ArrayList<Student> getList() {
        return list;
    }

    public void addStudents() {
        list = new ArrayList<>();
        list.add(new Student("Joe Wilson", 16, 11));
        list.add(new Student("Bill Johnson", 16, 10));
        list.add(new Student("Joe Jonson", 15, 9));
        list.add(new Student("William Smith", 17, 12));
        list.add(new Student("Dan Smith", 16, 11));

    }

}

2 个答案:

答案 0 :(得分:2)

更改

for(int i = 0; i < list.size(); i++) {

for(int i = 0; i < (list != null) ? list.size() : 0; i++) {

或者,如果你不喜欢三元运算符(它相当难看)。在for循环之前添加这些行

if (list == null || list.size() < 1) {
  return "No Records Found!";
}

答案 1 :(得分:2)

问题是你的Frame构造函数:

public Frame() {
    Objects a = new Objects(); //<-- new object of type Objects
    list = a.getList(); //<-- call getList but list is null
}

可能有两种解决方案:

<小时/> 保持当前的构造函数:

public Frame() {
        Objects a = new Objects(); 
        a.addStudents(); // <-- calling this method will initialize your list
        list = a.getList();
}

<小时/> 考虑传递Objects对象(顺便说一句,你应该使用另一个名字)作为参数:

public Frame(Objects a) {
    list = a.getList(); //<-- call getList but list is null
}

然后在你的主要:

Frame f = new Frame(a);