简体   繁体   中英

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.

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];

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.

Well, i don't think that you can perform copy or even a simple call unless you address you array in "proper way".

So something like

array[0]=array[1];

or

array[0][1]=array[1][1];

won't work but if you write

array[0][0][0]=array[1][0][0];

it will work, i'm guessing because the compiler is sure you are talking about the same array here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM