Why does the foreach statement not change the element value?

前端 未结 6 1223

How come the following prints boss and not bass?

String boss = \"boss\";
char[] array = boss.toCharArray();

for(char c : array)
{
 if (c== \'o\')
     c =          


        
6条回答
  •  我寻月下人不归
    2020-11-22 01:11

    You're changing the iteration variable c. That doesn't change the contents of the array. The iteration variable is just a copy of the array element. If you want to modify the array, you need to do so explicitly:

    for (int i = 0; i < array.length; i++) {
        if (array[i] == 'o') {
            array[i] = 'a';
        }
    }
    

    Your original code is equivalent (as per section 14.14.2 of the JLS) to:

    for (int i = 0; i < array.length; i++) {
        char c = array[i];
        if (c == 'o') {
            c = 'a'; 
        }
    }
    

    Changing the value of a local variable will never change anything else - it just changes the local variable. The assignment:

    char c = array[i];
    

    copies the value in the array into a local variable. It doesn't associate the local variable with the array element perpetually.

提交回复
热议问题