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.

0

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

5 Comments

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, you can do if(arcs[i] == null) { arcs[i] = new Arcs(); }. There may be a cleaner way to handle that, though.
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 :)
arcs = new Arcs[n] initializes a container for n Arcs objects, but it doesn't create the objects itself, by design.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.