使用foreach循环更改2D数组中的值
我在Java中遇到了一个有趣的夸克.
I have encountered an interesting quark in Java.
此代码段将按预期执行(将数组内的所有值更改为0):
This code segment will execute as expected (change all values inside the array to 0):
int[][] test = {{4, 2, 6}, { 7, 4, 10 }, { 3, 4, 1 } };
for (int[] current : test) {
current[0] = 0;
current[1] = 0;
current[2] = 0;
}
但是这不会:
int[][] test = {{4, 2, 6}, { 7, 4, 10 }, { 3, 4, 1 } };
for (int[] current : test) {
for (int num : current) {
num = 0;
}
}
感谢您的帮助.预先感谢.
Any help is appreciated. Thanks in advance.
为澄清起见,我理解为什么第二个代码段不起作用.我想知道为什么第一部分有效.谢谢.我不是要寻找这将起作用"的答案,而是想知道第一个细分与第二个细分的区别是什么.
To clarify, I understand why the second code segment does not work. I'm wondering why the first segment works. Thanks. I am not looking for "this will work" responses, I want to know what distinguishes the first segment from the second.
您仅对 local
变量进行了更改.它不会影响您遍历的数组.
You are making your change to a local
variable only. It does not impact the array you are traversing.
for-each
循环只是与 iterator
一起合成的for循环糖.
for-each
loop is just a synthetic sugar for loop with iterator
.