爪哇 - NullPointerException异常的Array [英] 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;
这是不是在构造函数初始化,因为我不知道我的向量的长度还,但它是在读的功能,在这里我从文件中读取的信息初始化。
在这个函数中我做到以下几点:
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
再有就是在我从文件中读取其他的东西了一会儿周期和我有类似:
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异常,我不明白为什么。我想AP preciate它,如果有人向我解释发生了什么。
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.
推荐答案
您确实曾经存放了弧
对象弧线[我]
?如果不是的所有元素弧[]
将被初始化为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 Tutorial: Arrays
这篇关于爪哇 - NullPointerException异常的Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!