0

I was just experimenting with a two dimensional array of classes in java. I wrote the following (wrong) code:

public class GameEvent
{
    static int LAUNCH_ALIEN = 0;
    static int END = 1;

    long time;
    long cum_time;
    int alien_type;
    int event_code;
}

then

GameEvent[][] event_array = new GameEvent[MAX_LEVELS][MAX_EVENTS];

and accessed it with code like below (read comment in code):

event_array[lev][ctr].event_code = code; // nullpointer exception at runtime

So my question now is, what is the least painful way to change my code so that it works.

3
  • how does it not work? Commented May 14, 2013 at 16:12
  • Just initialize the array and it will work. Commented May 14, 2013 at 16:12
  • because that position is pointing to null :) Commented May 14, 2013 at 16:14

1 Answer 1

3
GameEvent[][] event_array = new GameEvent[MAX_LEVELS][MAX_EVENTS];

This allocates the array of references to GameEvent objects but not the objects themselves.

To actually allocate the obects it is necessary to do it for every cell of the array:

for (int i = 0; i < MAX_LEVELS; ++i)
  for (int j = 0; j < MAX_EVENTS; ++j)
    event_array[i][j] = new GameEvent();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.