简体   繁体   English

在Java中初始化自定义类的二维数组

[英]Initializing a 2d array of custom class in java

I'm getting a NullPointerException when I try to instantiate a class that contains a 2d array of interface. 尝试实例化包含2d接口数组的类时,出现NullPointerException异常。 In a other class i have an Object of type CompetitionGround and i try to do something like this to initialize it: 在另一个类中,我有一个类型为CompetitionGround的对象,我尝试执行以下操作来初始化它:

CompetitionGround groud;
ground=new CompetitionGround(5);

My constructor for the class CompetitionGround looks like this: 我的CompetitionGround类的构造函数如下所示:

public CompetitionGround(int boundries) {
    for (int i = 0; i <boundries; i++)
        for (int j = 0; j <boundries; j++)
            eggs[i][j]=new Egg();
}

and the whole class is: 整个类是:

public class CompetitionGround {

    private IEgg eggs[][];

    public void goIn(Rabbit rabbit) {
        IPozition temp = rabbit.getPozition();
        rabbit.Collect(eggs[temp.getPozitionX()][temp.getPozitionY()]);
    }

    public CompetitionGround(int boundries) {
        for (int i = 0; i < boundries; i++)
            for (int j = 0; j < boundries; j++)
                eggs[i][j] = new Egg();
    }

    public void AddEgg(int x, int y, int points) {
        eggs[x][y] = new Egg(points);
    }
}

Class Egg that implements IEgg has two types of constructors. 实现IEgg的Egg类具有两种构造函数。 I tried with both and get the same problem. 我尝试两者,并得到相同的问题。 What am I doing wrong? 我究竟做错了什么? I can't figure it out. 我不知道。

The array itself was never initialized, so you can't assign anything to its elements yet. 数组本身从未初始化过,因此您还不能为它的元素分配任何东西。 Before initializing in the 2 nested for loop, create the 2D array itself first. 在初始化2个嵌套的for循环之前,请先创建2D数组本身。

public CompetitionGround(int boundries  /* [sic] */) {
    // Init array here.
    eggs = new IEgg[boundries][boundries];

    // You should use proper indenting.
    for (int i = 0; i < boundries; i++)
       for (int j = 0; j < boundries; j++)
           eggs[i][j] = new Egg();
}

You aren't ever initializing eggs , which is causing your issues. 您永远不会初始化eggs ,这会引起您的问题。 Right now you are initializing each element of eggs , but that will give you problems if you don't initialize eggs itself first. 现在,您正在初始化eggs每个元素,但是如果您不首先初始化eggs本身,那将会给您带来麻烦。

I recommend doing this in the constructor like this: 我建议在构造函数中执行以下操作:

public CompetitionGround(int boundries)
{
    //Remember, you want IEgg, not Egg here
    //This is so that you can add elements that implement IEgg but aren't Eggs
    eggs = new IEgg[boundries][boundries];

    for (int i = 0; i <boundries; i++)
    {
        for (int j = 0; j <boundries; j++)
        {
            eggs[i][j]=new Egg();
        }
    }
}

Also, this is unrelated, but boundaries is spelled wrong. 同样,这无关紧要,但是边界拼写错误。 Could cause problems later. 以后可能会引起问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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