Java - 数组中的 NullPointerException [英] Java - NullPointerException in Array
问题描述
我遇到了以下问题:我有一个带有私有成员的 java 类,如下所示:
I have encountered the following problem: I have a java class with a private member like so:
private Arcs[] arcs;
这不是在构造函数中初始化,因为我还不知道向量的长度,但它是在 read 函数中初始化的,我从文件中读取信息.在这个函数中,我执行以下操作:
This is not initialised in the constructor because I don't know the length of my vector yet, but it is initialised in the read function, where I read the info from a file. In this function I do the following:
arcs = new Arcs[n]; //n is a number read from file
然后有一个while循环,我从文件中读取其他内容,我有类似的东西:
Then there is a while cycle in which I read other stuff from the file and I have something like:
while(condition){
...
arcs[i].add(blah); //i is a valid number, smaller than n, and the add function is also correct
...
}
但是在这里我有一个错误说 NullPointerException 并且我不明白为什么.如果有人向我解释发生了什么,我将不胜感激.
But here I have an error saying NullPointerException and I don't understand why. I would appreciate it, if someone would explain to me what's happening.
推荐答案
您是否真的在 arcs[i]
中存储了 Arcs
对象?如果不是,arcs[]
的所有元素都将被初始化为 null.(因此是 NPE)
Are you actually ever storing an Arcs
object in arcs[i]
? If not, all elements of arcs[]
will be initialized to null. (Hence the NPE)
做这样的事情:
while(condition){
// ...
arcs[i] = new Arcs();
arcs[i].add(blah);
// ...
}
参考:
- Java 教程:数组
这篇关于Java - 数组中的 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!