Sucea Cosmin
Sucea Cosmin

Reputation: 33

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. In a other class i have an Object of type CompetitionGround and i try to do something like this to initialize it:

CompetitionGround groud;
ground=new CompetitionGround(5);

My constructor for the class CompetitionGround looks like this:

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. I tried with both and get the same problem. What am I doing wrong? I can't figure it out.

Upvotes: 1

Views: 10246

Answers (2)

rgettman
rgettman

Reputation: 178303

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.

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

Upvotes: 1

Akshay
Akshay

Reputation: 812

You aren't ever initializing eggs, which is causing your issues. Right now you are initializing each element of eggs, but that will give you problems if you don't initialize eggs itself first.

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.

Upvotes: 0

Related Questions