简体   繁体   English

For Each Loop 编辑原始二维数组

[英]For Each Loop Editing Original 2D Array

In the for each loop, the output is 6. However, I thought that the output would be 0 since, at least for one dimensional arrays, for each loops only traverse arrays.在 for each 循环中,输出为 6。但是,我认为输出将为 0,因为至少对于一维数组,每个循环只遍历数组。 How is "g" being edited if "f" is only a local variable in the loop?如果“f”只是循环中的局部变量,如何编辑“g”?

int[][] g = new int[7][7];

for(int[] f : g) {
    for(int h = 0; h < f.length; h++)
        f[h] = 6;
}

System.out.println(g[4][6]);

Even though Java is pass-by-value , if the values you pass are references to mutable data types, they can be mutated.尽管 Java 是按值传递的,但如果您传递的值是对可变数据类型的引用,则它们可以被改变。

As you know, f is the value that you're iterating over in an enhanced-for loop, but it represents each element contained inside of your two-dimensional array g .如您所知, f是您在增强型 for 循环中迭代的值,但它表示二维数组g包含的每个元素。

In this scenario, it's your int[] that is mutable.在这种情况下,您的int[]是可变的。 You are actively editing the values in your two-dimensional array to another value entirely.您正在积极地将二维数组中的值完全编辑为另一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM