本文介绍了创建对象数组时出现 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试创建一个包含两个值的类的数组,但是当我尝试将一个值应用于该数组时,我得到了一个 NullPointerException.
I have been trying to create an array of a class containing two values, but when I try to apply a value to the array I get a NullPointerException.
public class ResultList {
public String name;
public Object value;
}
public class Test {
public static void main(String[] args){
ResultList[] boll = new ResultList[5];
boll[0].name = "iiii";
}
}
为什么我会收到此异常,我该如何解决?
Why am I getting this exception and how can I fix it?
推荐答案
您创建了数组但没有在其中放入任何内容,因此您有一个包含 5 个元素的数组,所有元素都为空.你可以添加
You created the array but didn't put anything in it, so you have an array that contains 5 elements, all of which are null. You could add
boll[0] = new ResultList();
在您设置 boll[0].name 的行之前.
before the line where you set boll[0].name.
这篇关于创建对象数组时出现 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!