在java中初始化自定义类的2d数组

时间:2014-07-22 18:24:32

标签: java arrays nullpointerexception polymorphism multidimensional-array

当我尝试实例化包含2d接口数组的类时,我得到了NullPointerException。 在另一个类我有一个类型为CompetitionGround的对象,我尝试做这样的事情来初始化它:

CompetitionGround groud;
ground=new CompetitionGround(5);

我的类ArenaGround的构造函数如下所示:

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

全班是:

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

实现IEgg的Class Egg有两种类型的构造函数。我试过两个并得到同样的问题。我究竟做错了什么?我无法弄清楚。

2 个答案:

答案 0 :(得分:1)

数组本身从未初始化,因此您无法为其元素分配任何内容。在初始化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();
}

答案 1 :(得分:0)

您无法初始化eggs,这会导致您的问题。现在您正在初始化eggs的每个元素,但如果您不首先初始化eggs,那么这会给您带来问题。

我建议在构造函数中执行此操作:

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

此外,这是无关的,但边界拼写错误。可能会在以后引起问题。