有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有没有一种方法可以使用forEach将值分配到数组中?

我对编程非常陌生,并学习了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循环


共 (1) 个答案

  1. # 1 楼答案

    简短回答:不,没有办法

    更详细的回答:对于每个循环,你会丢失索引信息,也就是说,在循环中,你不知道你是在处理第一个、第二个还是第一百个元素。需要索引来寻址数组中要写入的位置。因此,只使用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 (int element : arr) {
        // the current index is unknown here
        use(element);
    }