Archived

This topic is now archived and is closed to further replies.

Metal Typhoon

Making a multidimensional array in java

Recommended Posts

i know that the following way can be used to do a multidimensional array ... public class Foo { int arr[][] = new int [8][8]; public void Test () {arr[0][0] = 1;} } but i''m running into problems. My problem is the following : i''m doing a private class inside Foo ,that would be like a struct in c++ , and trying to make a multidim array out of it.. but when i compile and try to access the array it says null pointer.. code below public class Foo { private class Foo2 { public int row = 0; public int col = 0; } public void Test () { Foo2 arr[][] = new Foo2 [8][8]; arr[0][0].row = 1; //<-- Null ?? } } but if i do a NON array variable it works just fine... can someone explain what i''m doing wrong here ?

Share this post


Link to post
Share on other sites
Yep - when you create an array of reference types (i.e. objects), you need to specifically create an object for each element of the array. For instance:


// This is correct as it tells Java to make room for our objects

Foo2 arr[][] = new Foo2 [8][8];

// We need to loop through to create a new object for each element

for ( int i = 0; i < 8; i++ ) {
for ( int j = 0; j < 8; j++ ) {
arr[i][j] = new Foo2;
}
}

arr[0][0].row = 1;


- Nanoprobe

Share this post


Link to post
Share on other sites
Yup. Just remind yourself that every non-primitive data type is like a pointer, so when you make a "new Foo2 [8][8]", then you''re really making an 8x8 array of pointers.

Share this post


Link to post
Share on other sites