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]?
CodePudding user response:
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.
CodePudding user response:
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
}
CodePudding user response:
please check the definition from the mdn
The forEach() method executes a provided function once for each array element.
If you want to change the value of the element of the array. you might use the map() method