为什么您可以使用for-each循环更改数组元素的值?

发布于 2025-01-20 19:16:46 字数 234 浏览 3 评论 0原文

输入图片这里的描述

我知道答案是它们都不起作用,但是为什么不能使用 for-each 循环更改数组元素的值呢?另外,对于顶部的代码段,要更新每个值,为什么不需要将其重新分配给numbers[j]?

enter image description here

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深海里的那抹蓝 2025-01-27 19:16:46

在 for-each 循环的主体中,您将获得数组中每个元素的本地副本(或实现 Iterable 就此而言)。对循环变量执行的任何操作都是针对本地副本,而不是数组元素本身。因此,这个 for-each 循环:

for (int num : numbers) {
  num++;
}

或多或少被编译为:

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

由于原始类型(如 int )是值类型(它们包含一个值,而不是对另一个值的引用),因此复制它会创建一个独立的价值副本。如果使用引用类型,则复制的值就是引用本身,因此对循环变量所做的任何更改都会反映在引用的对象上。这就是为什么它有效:

class IntHandle {
  int value;
  IntHandle(int value) {
    this.value = value;
  }
}

var numbers = new IntHandle[] {new IntHandle(1)};
for (var num : numbers) {
  num.value++; // Equivalent to numbers[i].value++
}

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:

for (int num : numbers) {
  num++;
}

is more or less compiled as:

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

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:

class IntHandle {
  int value;
  IntHandle(int value) {
    this.value = value;
  }
}

var numbers = new IntHandle[] {new IntHandle(1)};
for (var num : numbers) {
  num.value++; // Equivalent to numbers[i].value++
}
苏佲洛 2025-01-27 19:16:46

好吧,您 can - 但是您需要使用for -east循环的东西来包含有效数组索引的范围。例如,使用intstream在Java 8+中,就像

IntStream.range(0, numbers.length).forEach(j -> numbers[j]++);

您无法使用(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 an IntStream in Java 8+ like

IntStream.range(0, numbers.length).forEach(j -> numbers[j]++);

The reason you can't do that with a for (int x : numbers) is because the for-each loop hides the Iterator or iteration mechanism.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文