gpt4 book ai didi

java - 有没有办法使用 forEach 将值分配到数组中?

转载 作者:行者123 更新时间:2023-12-02 01:06:57 24 4
gpt4 key购买 nike

我对编程很陌生,并且学习了 Java 中的 forEach 循环。据我所知,这是经典 for 循环的较短版本。我的问题是,如何使用 forEach 将值保存到数组中还是只读?

int[] arr = new int[5];

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

for (int i : arr) {
arr[i] = i;
}

但是我的数组是[0,0,0,0,0]。 (当然是,但是我可以修改它吗?)

如果没有,除了普通的 for 循环之外还有其他方法吗?

最佳答案

简短回答:不,没有办法。

更长的答案:使用 for-each 循环,您会丢失索引信息,即在循环中,您不知道正在处理第一个、第二个还是第一百个元素。您需要索引来寻址数组中要写入的位置。因此,仅使用 for-each 是没有办法的。

Mind: In your example the first loop just overwrites the array's elements with their indexes. You'll get arr = { 0, 1, 2, 3, 4 }. The second loop only works, because it iterates over an arrays whose elements are their own indexes by chance–as you defined it that way before.

If your array for example was `arr = { 42, 101, -73, 0, 5 }' the first iteration would try to access the 43nd element of an array with only five elements, thus causing an exception.

您可以创建并递增自己的索引计数器,但这实际上是传统 for 循环以非常方便的方式所做的事情。

传统的for循环:

for (int index = 0; index < arr.length; index++) {
var element = array[index];
use(element);
}

for-each 循环:

for (int element : arr) {
// the current index is unknown here
use(element);
}

关于java - 有没有办法使用 forEach 将值分配到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59894380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com