【问题标题】:Java: Foreach loop not working as expected on int array? [duplicate]Java:Foreach 循环在 int 数组上没有按预期工作? [复制]
【发布时间】:2011-08-28 00:41:12
【问题描述】:

我有一个非常简单的循环:

int[] positions = {1, 0, 0}

//print content of positions

for (int i : positions)
{
    if (i <= 0) i = -1;
}

//print content of positions

现在,我期望得到的是:

array: 1, 0, 0
array: 1, -1, -1

但我得到了

array: 1, 0, 0
array: 1, 0, 0

只是……为什么?

亲切的问候, 水母

【问题讨论】:

    标签: java arrays loops foreach


    【解决方案1】:

    因为“i”是数组元素的副本,而不是对它的引用 :) 您修改的是局部变量,而不是数组的元素

    这段代码相当于

    for(int index = 0; index < array.length; index++) {
    
    int i = array[index];
    ...
    }
    

    【讨论】:

    • 我花了很长时间才找到这个答案......我有一个数组,正在 foreach 中实例化对象,稍后用索引访问它们,我得到空指针异常。所以 for 和 foreach 不一样...
    【解决方案2】:

    这很简单。如果你写

    int i = positions[0];
    

    然后你按值复制positions[0],而不是按引用。您不能从i 修改positions[0] 中的原始值。这同样适用于在 foreach 循环中分配 i

    解决方案是没有foreach循环

    for (int i = 0; i < positions.length; i++)
    {
        if (positions[i] <= 0) positions[i] = -1;
    }
    

    【讨论】:

      【解决方案3】:

      如果我们对数组使用增强的 for 循环,这会在幕后发生:

      int[] array = {1,2,3,4,5};
      for($i = 0; $i<array.length; $i++) {
        int i = array[$i];
        // your statements
        if (i <= 0) i = -1;
      }
      

      $i 只是一个未命名的内部循环变量的占位符。看看会发生什么:您为i 分配了一个新值,但i 在下一次迭代中加载了下一个数组项。

      所以,实际上,我们不能使用增强的for循环中声明的变量来修改底层数组。

      参考:JLS 3.0, 14.14.2

      【讨论】:

        猜你喜欢
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        • 2017-03-29
        • 2013-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多