0

I'm trying to copy an Object I've created from one array to another of the same type in Java. When I run my program I receive a NullPointerException.

The relevant class functions are:

private int mState;
public Cell(int pRow, int pColumn, int pState) {
    //other things
    setState(pState);
}

public void setState(int pNewState) {
    mState = pNewState;
}

public void setDead() {
    mState = DEAD;
}

and the line in which the error occurs:

mFutureGeneration[i][j].setDead();

That array is defined as

private Cell [][] mFutureGeneration;

then dimensioned as

mFutureGeneration = new Cell[100][100]; 

It receives its contents from:

Cell [][] vSeedArray = new Cell[100][100]; 

which is filled as

for (int i = 0; i<100; i++) {
    for (int j = 0; j<100; j++) {
        int vNewState = mGenerator.nextInt(2) - 1;
        vSeedArray[i][j] = new Cell(i,j,vNewState);
    }
}

I think the problem is happening in the copy, but I was always under the impression Java copied by reference, so I can't see why it would be failing.

I copy the contents across with a loop

for(int i = 0; i<vSeedArray.length; i++) {
    for(int j=0; j<vSeedArray[i].length; j++) {
            mCurrentGeneration[i][j] = vSeedArray[i][j];
    }
}

Any help would be appreciated.

Thanks.

4
  • 1
    how does mCurrentGeneration get to mFutureGeneration? Commented Oct 31, 2012 at 1:02
  • 1
    I suggest that you start by using your debugger (or adding SOP statements). Check the values of i, j, and mFutureGeneration[i][j] at the line with mFutureGeneration[i][j].setDead();. Commented Oct 31, 2012 at 1:02
  • @EliAlgranti That was the problem. I have two array's mFutureGeneration and mCurrentGeneration I've been refactoring from using a simple 0 and 1 in the array to having an object, and forgot to actually create objects in the mFutureGeneration array. Thanks! Commented Oct 31, 2012 at 1:09
  • @xyzjace - no prob sometimes you just need someone to ask you "Are you sure you turned it on?" :-) Commented Oct 31, 2012 at 11:52

1 Answer 1

3

I'm not sure you're ever allocating any "Cell" objects - just the array to hold them.

If so, that's probably the cause of your NullPointer exception.

Good link:

Scroll down to the section "Array of Objects".

'Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.