在Java中的ArrayList中的元素修改时foreach循环不工作
检查了这一点:
import java.util.ArrayList;
public class passbyReferenceOrValue {
public static void main(String[] args) {
ArrayList<String> c=new ArrayList<>();
c.add("abc");
for (String k : c) {
k+="l";
}
System.out.println(c);
}
}
结果是[ABC],为什么呢?
好吧,为了发布这个问题我不得不添加更多的细节,那就是这是一个测试code我写的,因为我遇到了使用for-each循环的另一个问题,当我这样做,我真的饿了,需要一个伟大的晚餐,顺便说一句,我认为这是不够的详细信息
result is [abc], why? Well, in order to post this question I have to add more detail, that is this is a testing code I wrote because i met another problems using for-each loop, and when I was doing that, I`m hungry and need a great dinner, by the way, I think it is enough for the "details"
在您从 ArrayList中获得
键,将其存储在字符串
值每次循环迭代 K
的参考,像
In each loop iteration you are getting String
value from ArrayList
and storing it in k
reference, something like
for (int i = 0; i < c.size(); i++) {
String k = c.get(i);//now k is reference to object from list
}
接下来,在 K + =L;
你正在做的是执行 K = K +L
这将创造新的字符串,并将其放在 K
引用
Next in k+="l";
all you are doing is executing k = k + "l"
which will create new string and place it in k
reference
String k = c.get(i);//now k is reference to object from list
k = k + "l"; //now k holds new object
所以这并不影响的ArrayList
。
如果你想改变抗衡ArrayList的,那么你不应该通过每个循环,但通过正常的循环像
If you want to change contend of ArrayList then you shouldn't be doing it via for each loop but via normal for loop like
for (int i = 0; i < c.size(); i++) {
c.set(i, c.get(i)+"l");
}