Java的:Foreach循环不工作int数组的预期? [英] Java: Foreach loop not working as expected on int array?
本文介绍了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];
...
}
这篇关于Java的:Foreach循环不工作int数组的预期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文