Stan
Stan

Reputation: 38255

Java how to get 1D array reference from a 2D array

Say I have a 2D array:

int[][] foo = new int[3][10];

I want to have a better alias name for each 1D array, like:

int[] xAxis = foo[0];
int[] yAxis = foo[1];
int[] zAxis = foo[2];

Is xAxis a reference to the 1st 1D array in 2D array? Cause I don't want the array to be copied again. If not, how do I get the reference to 1D arrays.

Upvotes: 2

Views: 2408

Answers (5)

Matthew
Matthew

Reputation: 302

I just tried out this code.

    int[][] foo = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    int[] xAxis = foo[0];
    int[] yAxis = foo[1];
    int[] zAxis = foo[2];

    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            foo[i][j]++;
        }
    }

    for(int i=0;i<3;i++){
        System.out.println("X: " + xAxis[i] + " Y: " + yAxis[i] + " Z: " + zAxis[i]);
    }

And yes, it indeed does reference it.

Upvotes: 0

Matteo Rubini
Matteo Rubini

Reputation: 831

http://www.functionx.com/java/Lesson22.htm

...with one-dimensional arrays, when passing an multi-dimensional array as argument, the array is treated as a reference. This makes it possible for the method to modify the array and return it changed

when you declare this

new int[3][10]

you got one object array with 3 values: array1, array2, array3. All arrays will share the same defined size (10)

so, yes! in this case, foo[0] -> array1[10] , foo[1] -> array2[10] and foo[2] -> array3[10]

consider this one: what did you expect if foo[0] didn't pointing to another array? how (foo[x])[y] should works?

Upvotes: 2

Codebender
Codebender

Reputation: 14438

Yes, array's are not primitive types, instead they are reference types.

So in your case xAxis will be a reference to foo[0]. Which means changes will be visible in both foo[0] and xAxis.

But you need to change your first statement to,

int[][] foo = new int[3][10];

Upvotes: 1

Mureinik
Mureinik

Reputation: 311808

Short answer - yes. The statement int[] xAxis = foo[0]; assigns the 1D array in foo[0] to the variable xAxis. Since arrays in Java are objects, this just assigns a reference. The data isn't being copied again.

Upvotes: 1

Panther
Panther

Reputation: 3339

Yes it is reference to 1st Array in 2nd Array. You can verify it by yourself by modifing the xAxis array and check if reflects in 1st 1D array of 2D array.

Upvotes: 1

Related Questions