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);
}
forEachmethod 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) { ... }int[] arr = IntStream.range(0, 5).toArray();.forEach, that is a method used in streams; it is called enhanced for loop or, commonly known as for-each loop