使用foreach循环更改2D数组中的值 [英] Using a foreach loop to change values in a 2D array

查看:36
本文介绍了使用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.

这篇关于使用foreach循环更改2D数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆