开发者

Java - NullPointerException in Array [duplicate]

开发者 https://www.devze.com 2023-01-23 02:45 出处:网络
This question already has answers here: NullPointerException when Creating an Array of objects [duplicate]
This question already has answers here: NullPointerException when Creating an Array of objects [duplicate] 开发者_开发问答 (9 answers) Closed 8 months ago.

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
...
}

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.


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)

Do something like this:

while(condition){
    // ...
    arcs[i] = new Arcs();
    arcs[i].add(blah); 
    // ...
}

Reference:

  • Java Tutorial: Arrays
0

精彩评论

暂无评论...
验证码 换一张
取 消