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
精彩评论