这段代码给了我一个NullPointerException
。其目的是循环遍历 ArrayList 并返回与参数年龄匹配的任何记录。
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));
}
}
最佳答案
问题出在你的 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
}
然后在你的 main 中:
Frame f = new Frame(a);
关于java - 为什么这个 for 循环会给我一个空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20166381/