tags:

views:

56

answers:

1

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

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

private void 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;
    }
}
+6  A: 

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.

Matthew Flaschen
Had I thought more about it, this would have been obvious. I think I was blinded by the bug this introduced. Very nice answer.
maleki