problemofficer problemofficer - 1 year ago 105
Java Question

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.

Answer Source

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:


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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download