【问题标题】:Using a foreach loop to change values in a 2D array [duplicate]使用foreach循环更改二维数组中的值[重复]
【发布时间】:2015-08-02 14:06:48
【问题描述】:

我在 Java 中遇到了一个有趣的夸克。

此代码段将按预期执行(将数组内的所有值更改为 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;
    }
}

感谢任何帮助。提前致谢。

编辑:

为了澄清,我理解为什么第二个代码段不起作用。我想知道为什么第一部分有效。谢谢。我不是在寻找“这将起作用”的响应,我想知道第一段与第二段的区别。

【问题讨论】:

    标签: java multidimensional-array foreach


    【解决方案1】:

    您仅对 local 变量进行更改。它不会影响您正在遍历的数组。

    for-each 循环只是一个带有iterator 的合成糖 for 循环。

    【讨论】:

    • 谢谢,但是为什么第一个代码段有效?
    • 因为你明确地使用了数组。
    • 二维数组是对一维数组的引用的一维数组。
    • 非常感谢!我现在明白了。
    【解决方案2】:
    for(Iterator<Integer> num = current.iterator(); num.hasNext(); ) {
        num = 0;
    }
    

    这就是扩展 foreach 时发生的情况。您必须了解的是,在您的第一个 sn-p 中,Iterator 迭代一个名为“current”的单维数组,该数组通过引用传递。所以电流的任何变化都会反映在“温度”上。但是,整数是按值传递的,这就是为什么在您的第二个 sn-p 中,对“num”所做的更改不会反映在“current”中的原因。因此,您只是在更改与原始数组无关的其他一些变量的值。尝试打印以下内容以便更好地理解。

        int[][] test1 = {{4, 2, 6}, { 7, 4, 10 }, { 3, 4, 1 } };
        for (int[] current : test1) {
            for (int num : current) {
                System.out.println(num);
                num = 0;
            }
        }
    

    【讨论】:

    • 很好很详细的解释。
    • @PM77-1 谢谢你,先生!
    【解决方案3】:

    有一个库方法Arrays.fill 可以为一维数组设置相同的值。使用它,这样你的代码会干净又快速。

    int[][] test = {{4, 2, 6}, { 7, 4, 10 }, { 3, 4, 1 } };
    for (int[] current : test)
        Arrays.fill(current, 0);
    

    【讨论】:

      【解决方案4】:

      这将起作用:

      int[][] test = {{4, 2, 6}, { 7, 4, 10 }, { 3, 4, 1 } };
      for (int[] current : test)
          for (int i = 0; i < current.length; i++)
              current[i] = 0;
      

      【讨论】:

        猜你喜欢
        • 2018-03-13
        • 1970-01-01
        • 2013-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-05
        • 1970-01-01
        • 2012-03-22
        相关资源
        最近更新 更多