[英]How to create and use a two dimensional array of classes
I was just experimenting with a two dimensional array of classes in java. 我只是在用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. 这
GameEvent
引用数组分配给GameEvent
对象,而不是对象本身。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.