Java hates me. It wont let me make an array of objects

Started by
2 comments, last by agm_ultimatex 14 years, 11 months ago
I know there must be something I'm doing wrong but for the life of me I don't see it. Heres a tiny excerpt from my code which is causing the problem.

Alien[] aliens;
aliens=new Alien[10];
aliens[0].setX(10);  //<--- gives me a Null Pointer exception



Seems simple enough. My Alien class has a println function in the constructor to let me know it was invoked but it never executes. If I change aliens from an array to a single variable and then set it equal to "new Alien();" then the Alien constructor is invoked and I don't get the exception. I know that isn't very much information but what could possibly make an attempt to make an array of objects not work, even when making a single one works just fine?
Simplicity is the ultimate sophistication. – Leonardo da Vinci
Advertisement
In Java, not only do you have to create the array via new, you also have to populate the array via new. Iterate through your newly created array object and fill it with new Aliens.
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]
Quote:Original post by MikeTacular
In Java, not only do you have to create the array via new, you also have to populate the array via new. Iterate through your newly created array object and fill it with new Aliens.

That is to say, new Alien[10] creates a new array to hold objects (specifically, pointers to objects) not new objects themselves.
[Window Detective] - Windows UI spy utility for programmers
Yeah thats just creating an array of size 10 to hold 10 Alien objects. So what you would need to follow it up on is

Alien[10] aliens;aliens[0] = new Alien();aliens[1] = new Alien();// etc

This topic is closed to new replies.

Advertisement