1

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.

Sireny
  • 11
  • 1
  • 2

1 Answers1

9

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:

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • I can't do that, because I may reffer to the same arcs[i] in more than one loop and that would mean initialising it over and over and in the end i won't have in it all the information i need. i've also tried to do that just before the while but still not good. – Sireny Nov 01 '10 at 07:50
  • @Sireny, you can do `if(arcs[i] == null) { arcs[i] = new Arcs(); }`. There may be a cleaner way to handle that, though. – Matthew Flaschen Nov 01 '10 at 07:54
  • Ok, I tried that again, and now it works... I used a for cycle to initialise all elements and now it's okay. I just don't get it why it didn't work in the first place. Anyway, thanks for everyone's help :) – Sireny Nov 01 '10 at 07:55
  • `arcs = new Arcs[n]` initializes a container for n Arcs objects, but it doesn't create the objects itself, by design. – Sean Patrick Floyd Nov 01 '10 at 08:01
  • When you have programmed in C++ before this may indeed be surprising. In that case you need to know that there are no *objects containing other objects directly*, in Java they can only *point* to other objects. The same goes for arrays: Casually speaking you have declared an array of `Arcs`, but strictly speaking you have declared an array of *pointers to* `Arcs`, which is something entirely different. – Roland Illig Nov 04 '10 at 16:34