为什么foreach语句不改变元素值?

2022-01-30 00:00:00 foreach java

为什么下面的打印是boss而不是bass?

How come the following prints boss and not bass?

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

for(char c : array)
{
 if (c== 'o')
     c = 'a'; 
}
System.out.println(new String(array)); //How come this does NOT print out bass?It prints boss.

推荐答案

您正在更改迭代变量 c.这不会改变数组的内容.迭代变量只是数组元素的副本.如果你想修改数组,你需要明确地这样做:

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';
    }
}

您的原始代码是等效的(根据 部分JLS 的 14.14.2) 到:

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.

相关文章