为什么foreach语句不更改元素值

为什么foreach语句不更改元素值

本文介绍了为什么foreach语句不更改元素值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的印刷品为什么是老板而不是低音?

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.

这篇关于为什么foreach语句不更改元素值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:32