Skip to main content
GameDev.net gamedev.net
🔒 Locked

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

Started by ForeverNoobie May 18, 2009 at 5:27 PM 2 replies 2.7k views
Original Post
ForeverNoobie
ForeverNoobie
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
Cornstalks
Cornstalks
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.
XTAL256
XTAL256
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
agm_ultimatex
agm_ultimatex
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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.