Home >Java >javaTutorial >Why Doesn't Modifying a Character in a Java For-Each Loop Change the Original Array?
Diving into the Iteration Dilemma: Why Foreach Loop Assignments Don't Alter Underlying Data
Despite the intuitive appeal of directly modifying elements within a foreach loop, as seen in this Java snippet:
String boss = "boss"; char[] array = boss.toCharArray(); for(char c : array) { if (c== 'o') c = 'a'; } System.out.println(new String(array)); //Unexpected result: "boss"
the code surprisingly yields "boss" instead of the expected "bass."
Unveiling the Copy
The key to understanding this paradox lies in the nature of the iteration variable "c." Contrary to popular belief, "c" represents a mere copy of the array element at hand. Modifying "c" has no bearing on the original array contents.
Array Modification Demystified
To genuinely alter the array, explicit intervention is necessary:
for (int i = 0; i < array.length; i++) { if (array[i] == 'o') { array[i] = 'a'; } }
Here, the code accesses and modifies the actual array elements, resulting in the array being updated to reflect the desired changes.
Understanding JLS Interpretation
The Java Language Specification (JLS) interprets the original code as equivalent to:
for (int i = 0; i < array.length; i++) { char c = array[i]; if (c == 'o') { c = 'a'; } }
This decomposition emphasizes that "c" is merely a copy that cannot influence the array.
In essence, foreach loops provide a streamlined means of iterating over collections without interfering with their underlying structure. Direct array modification requires explicitly working with the array index and elements.
The above is the detailed content of Why Doesn't Modifying a Character in a Java For-Each Loop Change the Original Array?. For more information, please follow other related articles on the PHP Chinese website!