Home > Java > javaTutorial > Why Doesn't Modifying a Foreach Loop's Iteration Variable Change the Underlying Array?

Why Doesn't Modifying a Foreach Loop's Iteration Variable Change the Underlying Array?

Patricia Arquette
Release: 2024-12-20 13:06:16
Original
565 people have browsed it

Why Doesn't Modifying a Foreach Loop's Iteration Variable Change the Underlying Array?

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"?
Copy after login

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';
    }
}
Copy after login

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';
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template