为什么您可以使用for-each循环更改数组元素的值?
I know the answer is that none of them work, but why exactly can't you change the value of an element of an array using for-each loop? Also for the code segment at top, to update each value, why wouldn't you need to reassign it to numbers[j]?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 for-each 循环的主体中,您将获得数组中每个元素的本地副本(或实现
Iterable
就此而言)。对循环变量执行的任何操作都是针对本地副本,而不是数组元素本身。因此,这个 for-each 循环:或多或少被编译为:
由于原始类型(如 int )是值类型(它们包含一个值,而不是对另一个值的引用),因此复制它会创建一个独立的价值副本。如果使用引用类型,则复制的值就是引用本身,因此对循环变量所做的任何更改都会反映在引用的对象上。这就是为什么它有效:
In the body of a for-each loop, you're getting a local copy of each element in the array (or any other object that implements
Iterable
for that matter). Any operation you do to the loop variable are done to the local copy, and not the array element itself. So this for-each loop:is more or less compiled as:
Since primitive types (like
int
) are value types (they contain a value, not a reference to another value), copying it creates an independent value copy. If a reference type is used instead, the value copied is the reference itself, so any changes you make to the loop variable are reflected on the referenced object. That's why this works:好吧,您 can - 但是您需要使用
for -east
循环的东西来包含有效数组索引的范围。例如,使用intstream
在Java 8+中,就像您无法使用(int x:nymess)无法执行此操作的原因是因为
for-每个
循环 隐藏迭代器
或迭代机制。Well, you can - but you need the thing you are using
for-each
loop to contain the range of valid array indices. For example, with anIntStream
in Java 8+ likeThe reason you can't do that with a
for (int x : numbers)
is because thefor-each
loop hides theIterator
or iteration mechanism.