gpt4 book ai didi

java - 为什么更改整个数组行会产生奇怪的行为?

转载 作者:行者123 更新时间:2023-11-30 05:59:04 24 4
gpt4 key购买 nike

简单地说。为什么这会让我的代码在一段时间后出现故障。

//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;
}
}

而改为手动一一更改就可以了。

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

最佳答案

您有一个数组数组,因此您的第一个代码将外部数组的两个元素设置为同一个内部数组。

更简单的例子:

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

因此您可以将颜色的内存可视化,例如:

[0xcafebabe, 0xdeadbeef]

如果您这样做:

colors[1] = colors[0];

它是:

[0xcafebabe, 0xcafebabe]

现在扩展的结构是:

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

但是两行都是对位于相同内存位置的相同数组的引用。如果您这样做:

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

数组的数组仍然是:

[0xcafebabe, 0xcafebabe]

扩展后的结构现在看起来像:

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

这也称为 shallow copy .

关于java - 为什么更改整个数组行会产生奇怪的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3545049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com