Jump to content
  • Advertisement
Sign in to follow this  
ForeverNoobie

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

This topic is 3320 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!