为什么foreach语句不改变元素值? [英] Why does the foreach statement not change the element value?

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

问题描述

为什么下面的打印是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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆