开发者

Why does changing an entire Array row create odd behavior?

Simply put. Why did this make my code malfunction after awhile.

//Color[][] colorArr = new Color[Width][Height]();

private voi开发者_如何学Cd shiftRowsDown(int row) {
    for (int i = row; i > 0; i--)
    {
        colorArr[i] = colorArr[i - 1];//<--This in particular
    }
    for (int col = 0; col < colorArr[0].length; col++) 
    {
        colorArr[0][col] = null;
    }
}

while changing it to manually change one by one was fine.

private void shiftRowsDown(int row) {
    for (int i = row; i > 0; i--) {
        for(int col = 0;col < colorArr[i].length;col++)
        {
        colorArr[i][col] = colorArr[i - 1][col];//<--This in particular
        }
    }
    for (int col = 0; col < colorArr[0].length; col++) 
    {
        colorArr[0][col] = null;
    }
}


You have an array of arrays, so your first code sets two elements of the outer array to the same inner array.

Simpler example:

Color[][] colors = new Color[2][2];
colors[0] = new Color[]{Color.red, Color.blue}; // colors[0] holds a reference to an array object, located at, say, 0xcafebabe
colors[1] = new Color[]{Color.orange, Color.yellow}; // Say color[1] a reference to an array at 0xdeadbeef

So you can visualize colors' memory like:

[0xcafebabe, 0xdeadbeef]

If you then do:

colors[1] = colors[0];

it is:

[0xcafebabe, 0xcafebabe]

The expanded structure is now:

{{Color.red, Color.blue}, {Color.red, Color.blue}}

But both rows are references to the same array, at the same memory position. If you then do:

colors[1][0] = Color.yellow;

the array of arrays is still:

[0xcafebabe, 0xcafebabe]

and the expanded structure now looks like:

{{Color.yellow, Color.blue}, {Color.yellow, Color.blue}}

This is also called a shallow copy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜