增强的for循环不适用于为数组赋值(Java) [英] Enhanced for loop not working for assigning values to an array (Java)
问题描述
我不明白为什么我不能使用增强的for循环为数组的元素赋值。
例如,像那样使用for循环
I don't understand why I cannot assign values to the elements of an array using the enhanced for loop. For example, using for loop like that
int[] array = new int[5];
for(int i = 0; i < 5; i++)
array[i] = 10;
产生我想要的东西。
但为什么这不适用于for each:
produces what I want. But why does that not work with "for each":
for(int element : array)
element = 10;
为什么会出现这种情况或者我做错了什么具体原因?
Is there any specific reason why that is the case or am I doing something wrong?
推荐答案
在增强型for循环中元素
是一个包含引用(或值)的局部变量在基元的情况下)到数组的当前元素或 Iterable
你正在迭代。
In the enhanced for loop element
is a local variable containing a reference (or value in case of primitives) to the current element of the array or Iterable
you are iterating over.
分配给它不会影响数组/ Iterable
。
Assigning to it doesn't affect the array / Iterable
.
它相当于:
int[] array = new int[5];
for(int i = 0; i < 5; i++) {
int element = array[i];
element = 10;
}
这也不会修改数组。
如果你需要修改数组,请使用常规for循环。
If you need to modify the array, use should use a regular for loop.
这篇关于增强的for循环不适用于为数组赋值(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!