为什么JAVA的foreach不改变元素值? [英] Why JAVA foreach doesn't change element value?

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

问题描述

下面怎么打印老板而不是低音?

 字符串boss =boss; 
char [] array = boss.toCharArray(); (char c:array)


{
if(c =='o')
c ='a';

System.out.println(new String(array)); //如何不打印低音?它打印老板。


您正在更改迭代变量<$ c $ ç> C 。这不会改变数组的内容。迭代变量只是数组元素的一个拷贝。如果你想修改数组,你需要明确地这样做:

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






你的原始代码是等价的(按照 JLS第14.14.2节):

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




$ b

改变局部变量的值不会改变任何东西否则 - 只是改变局部变量。作业:

  char c = array [i]; 

拷贝数组中的值变成局部变量。它不会将本地变量与数组元素永久关联。


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.

解决方案

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.

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

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