Enigmatic Assignment in Foreach Loops: Why It Doesn't Affect Underlying Data
Consider the perplexing code snippet below:
String boss = "boss"; char[] array = boss.toCharArray(); for(char c : array) { if (c== 'o') c = 'a'; } System.out.println(new String(array)); //Why does this print "boss" and not "bass"?
Despite the seeming assignment to the iteration variable c, the output remains "boss" instead of the expected "bass." To unravel this mystery, we delve into the nuances of the foreach loop.
Iteration Variable: A Mere Proxy
When iterating over a collection using a foreach loop, the iteration variable (in this case, c) merely represents a copy of the elements. Essentially, it acts as a temporary placeholder while accessing the underlying collection.
Modifying the Placeholder vs. Changing the Collection
Assignments made to the iteration variable only affect the copy and not the original collection. This is equivalent to:
for (int i = 0; i < array.length; i++) { char c = array[i]; if (c == 'o') { c = 'a'; } }
While the value of c is locally modified, the original array remains unchanged.
Imperative Modification for Real Change
To genuinely modify the underlying collection, direct access to the array elements is necessary:
for (int i = 0; i < array.length; i++) { if (array[i] == 'o') { array[i] = 'a'; } }
This code explicitly alters the individual elements of the array, resulting in the desired "bass" output.
Conclusion
Understanding the true nature of the iteration variable in foreach loops is crucial to avoiding confusion and ensuring effective data manipulation. By making assignments to the array elements instead of the iteration variable, developers can confidently modify the underlying collections according to their intended requirements.
The above is the detailed content of Why Doesn't Modifying a Foreach Loop's Iteration Variable Change the Underlying Array?. For more information, please follow other related articles on the PHP Chinese website!