0

I'm pretty new to programming and learned the forEach loop in Java. As far as I know it's a shorter version of the classic for loop. My question is, how can I save values into an array with forEach or is it read-only?

int[] arr = new int[5];

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

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

But my array is [0,0,0,0,0]. (Of course it is, but can I modify it somehow?)

If not is there another way instead of the normal for-loop?

6
  • 1
    A forEach method doesn't grant you direct access to indexes, only to the elements themselves... I mean the one that doesn't use streams... This: for (int i : arr) { ... } Commented Jan 24, 2020 at 10:20
  • 1
    you might be interested in Difference between for loop and Enhanced for loop in Java Commented Jan 24, 2020 at 10:29
  • int[] arr = IntStream.range(0, 5).toArray();. Commented Jan 24, 2020 at 10:37
  • 2
    "As far as I know it's a shorter version of the classic for loop" it's a severely limited form of an enhanced for loop. (You can't break/return, throw checked exceptions, assign variables from outside the lambda etc). Commented Jan 24, 2020 at 10:40
  • 2
    do not call it forEach, that is a method used in streams; it is called enhanced for loop or, commonly known as for-each loop Commented Jan 24, 2020 at 11:01

1 Answer 1

2

Short answer: no, there is no way.

Longer answer: With a for-each loop you lose the index information, i.e. within the loop you don't know if you are dealing with thefirst, the second or the hundredth element. You need the index to address the position to write to in the array. So with using only the for-each there is no way.

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.

You could create and increment your own index counter, but that's actually what the conventional for-loop does in a very convenient way.

conventional for loop:

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

for-each loop:

for (int element : arr) {
    // the current index is unknown here
    use(element);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.