[英]Error occured while using java foreach statements
My code as follows 我的代码如下
public class Test {
public static void main(String[] args) {
int count1 = 0, count2 = 0;
Test[] test1 = new Test[5];
Test[] test2 = new Test[5];
if (test1 == null || test2 == null)
System.out.println("null");
for (int j = 0; j < 3; j++) {
for (int i = 0; i < test1.length; i++) {
if (test1[i] == null) {
test1[i] = new Test();
count1++;
}
}
}
for (int j = 0; j < 3; j++) {
for (Test test : test2) {
if (test == null) {
test = new Test();
count2++;
}
}
}
System.out.println(count1 + " " + count2);
}
}
I run the program and I found its output is 5 15
. 我运行程序,我发现它的输出是5 15
。 It made me confused,I can't understand what differences between using for statements and using foreach statements.Thanks for giving me a hand. 这让我感到困惑,我无法理解使用for语句和使用foreach语句之间的区别。谢谢你帮助我。
Changes to the iteration variable in an enhanced-for statement do not affect the underlying collection. 对enhanced-for语句中的迭代变量的更改不会影响基础集合。 So while this modifies the array: 所以虽然这会修改数组:
test[i] = new Test(); // In for loop
... this doesn't: ......这不是:
test = new Test(); // In enhanced for loop
Because the array isn't modified, the next time you iterate over it, the values are still null, so you'll increment your counter another 5 times. 因为数组未被修改,所以下次迭代它时,值仍为空,因此您将计数器再增加5次。 Ditto the third time you iterate over the array. 第三次遍历数组时也是如此。
The moral of the story is: don't use an enhanced for loop if you want to modify the content of the collection/array. 故事的寓意是:如果要修改集合/数组的内容,请不要使用增强的for循环。
Note that changes to the objects whose references are already stored in the collection/array doesn't count as modifying the collection/array. 请注意,对其引用已存储在集合/数组中的对象的更改不计入修改集合/数组。 So if you'd already populated the collection and had some setName()
method, then this: 所以如果你已经填充了集合并且有一些setName()
方法,那么这个:
for (int i = 0; i < test1.length; i++) {
test[i].setName("foo");
}
would be equivalent to: 相当于:
for (Test test : test1) {
test.setName("foo");
}
That's not changing the array, which just contains references to objects - instead, it's changing the data within those objects. 这并没有改变数组,它只包含对象的引用 - 相反,它正在改变这些对象中的数据。
You can't modify the underlying data structure using the extended for-loop ("foreach"), your test = new Test();
您无法使用扩展的for循环(“foreach”)修改基础数据结构, test = new Test();
doesn't change the array. 不会更改数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.