Enhanced for loop cannot assign values to arrays (Java)
•
Java
See the English answer > why Java foreach doesn't change element value? 7
int[] array = new int[5]; for(int i = 0; i < 5; i++) array[i] = 10;
Produce what I want But why doesn't this fit "for everyone":
for(int element : array) element = 10;
Is there a specific reason for this or what I did wrong?
Solution
In the enhanced for loop element, it is a local variable that contains a reference to the current element of the array (or the value in the basic case) or iterative iteratable
Assigning to it does not affect the array / iteratable
It is equivalent to:
int[] array = new int[5]; for(int i = 0; i < 5; i++) { int element = array[i]; element = 10; }
The array will not be modified
If you need to modify the array, use the regular for loop
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码