Java的:Foreach循环不工作int数组的预期?

问题描述:

我有一个pretty简单的循环:

I've got a pretty simple loop:

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

//print content of positions

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

//print content of positions

现在,我会希望得到的是:

Now, what I would expect to get is:

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

而是我得到

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

只是......为什么?

Just... why?

亲切的问候,
水母

Kind regards, jellyfish

由于 I 是一个数组元素的副本,而不是对它的引用:)
您修改一个局部变量,而不是一个数组的元素

Because "i" is a copy of an array element and not a reference to it :) You modify a local variable, not an array's element

这code相当于

for(int index = 0; index < array.length; index++) {

int i = array[index];
...
}