Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array assignment vs. for loop assignment

In a class I have a private array

private boolean[][][] array;

that is later declared as

array = new boolean[2][100][100]; //*

At a certain point I want to overwrite the first array in the first dimension with the second array of the first dimension. I assumed this should work

array[0] = array[1];

but this yielded wrong behavior. I tried this plain for-loop:

for (int column = 0; column < array[0].length; column++) {
    for (int row = 0; row < array[0][0].length; row++) {
        array[0][column][row] = array[1][column][row];
    }
}

and it worked as expected.

Why didn't the first snippet of code work?

*The first dimension is static at 2 but the other actually come from another array. I removed them for clarity.

like image 963
problemofficer - n.f. Monica Avatar asked Mar 14 '23 10:03

problemofficer - n.f. Monica


2 Answers

The first snippet of code did not work because it does not copy the array dimension, it aliases it. Arrays are objects, so the assignment creates a second reference to the same dimension, and assigns it to the first dimension. That is why you get a different (and incorrect) behavior.

Here is an illustration of what is going on:

Reassignment

The assignment drops the 100x100 array from the top dimension at index zero, and replaces it with a reference to the 100x100 array at dimension 1. At this point any modification to the first array get reflected in the second array, and vice versa.

If you do not care about keeping the prior version of the array after re-assignment, you can assign a brand-new array to element 1, like this:

array[0] = array[1];
array[1] = new boolean[100][100];
like image 92
Sergey Kalinichenko Avatar answered Mar 16 '23 22:03

Sergey Kalinichenko


This line

array[0] = array[1];

States that the object reference stored in array[1] will be now also stored in array[0]. Since an array in Java is an object reference, now both array[0] and array[1] point to the same location.

If you want/need to clear the data of an array, use a loop: for, while, do-while, the one you feel more comfortable.

like image 39
Luiggi Mendoza Avatar answered Mar 17 '23 00:03

Luiggi Mendoza