【问题标题】:Initializing a 2d array of custom class in java在java中初始化自定义类的二维数组
【发布时间】:2014-09-13 17:17:12
【问题描述】:

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

CompetitionGround groud;
ground=new CompetitionGround(5);

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

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 的 Egg 类有两种类型的构造函数。我尝试了两者并遇到了同样的问题。我究竟做错了什么?我想不通。

【问题讨论】:

  • 语法建议:拼写为Position 而不是Pozitionboundaries 不是boundries
  • 看起来您正在访问一个空元素eggs,就像错误状态一样。初始化eggs。不要忘记考虑实际的错误。

标签: java arrays nullpointerexception polymorphism multidimensional-array


【解决方案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();
}

【讨论】:

  • 这个解决方案不是多态的
  • @asrivat1 出于某种原因,我没有看到IEgg。已更新。
  • 谢谢,你的解释帮了大忙!我正在尝试一件事或另一件事,甚至没想过要同时使用这两种方法。
【解决方案2】:

您从未初始化过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();
        }
    }
}

此外,这是不相关的,但边界拼写错误。以后可能会出现问题。

【讨论】:

  • 太棒了!如果对您有帮助,也请考虑接受此答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 2013-11-21
  • 2016-09-01
  • 2023-04-08
  • 1970-01-01
  • 2023-03-28
  • 2012-11-29
相关资源
最近更新 更多