简体   繁体   中英

How to create and use a two dimensional array of classes

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM