简体   繁体   English

增强型 for 循环中的循环变量

[英]Loop variable in enhanced for loop

The following works fine,以下工作正常,

int i;
for (i = 0; i < 10; i++) {}

But this doesn't但这不

// a is an ArrayList of Integers
Integer i;
for (i: a) {}

and I'm forced to do it this way:我被迫这样做:

for (Integer i : a) {}

Why is it that the second loop doesn't work?为什么第二个循环不起作用?

Think about it this way: What would happen if you always initialized your variable?这样想:如果你总是初始化你的变量会发生什么?

In the first case: It's initialized IN this example, clearly no problem.在第一种情况下:它在这个例子中被初始化,显然没问题。

In the second case: You initialize it, to say, 1. Now you have a variable, "1", and you throw it into this for loop.在第二种情况下:你初始化它,比如说,1。现在你有一个变量,“1”,你把它扔到这个 for 循环中。 "for( 1 : a)". “for(1:a)”。 What does that mean??这意味着什么?? And if you override the value of "i" for every value in a, then when it comes out of the loop it's simply the last entry in A. Again, what does that really mean?如果你为 a 中的每个值覆盖“i”的值,那么当它从循环中出来时,它只是 A 中的最后一个条目。同样,这到底是什么意思? Why would that be useful?为什么会有用? How does the effect the rest of the code outside of this loop?这个循环之外的其余代码如何影响? It's bad design to support that, it would result in all sorts of crazy, unexpected behavior and unreadable code.支持它是糟糕的设计,它会导致各种疯狂的、意外的行为和不可读的代码。

In the third case: Your variable is explicitly declared IN the scope of that loop, and is very clearly temporary.在第三种情况下:您的变量在该循环的范围内显式声明,并且非常明显是临时的。 It will do its job of extracting what you need from this array and be done with.它将完成从该数组中提取您需要的内容并完成的工作。 Any modifications to outside pieces of code will need to happen intentionally with explicit setters.对外部代码段的任何修改都需要使用显式设置器有意地进行。 Note that you can't initialize it here, because initializing is meaningless.注意这里不能初始化,因为初始化没有意义。

For the for loops, you need 3 statements.对于 for 循环,您需要 3 条语句。 Your second loop only has 2 statements, and your first one has 3. On top of that, you never initialized your integer i.您的第二个循环只有 2 个语句,而您的第一个循环有 3 个。最重要的是,您从未初始化过整数 i。 Make sure to do确保做

int i =0; 
for(i;i<=10;i++){
}

For enchanced for loops, you must have对于增强的 for 循环,您必须具有

for (String element : array) {
System.out.println("Element: " + element);
}

You can check out this link, it might help.您可以查看此链接,它可能会有所帮助。 What is the syntax of enhanced for loop in Java? Java中增强的for循环的语法是什么?

You have to explicitly give the type of object that you are iterating over in the array list.您必须在数组列表中明确给出要迭代的对象类型。 In the first for loop you are just plugging in the index.在第一个 for 循环中,您只是插入索引。 In the second, you are trying to have the for loop grab the object without knowing what kind of object it is.在第二种情况下,您试图让 for 循环抓取对象而不知道它是什么类型的对象。

The enhanced for statement is equivalent to a basic for statement of the form:增强的 for 语句等效于以下形式的基本 for 语句:

for (Iterator i = Expression.iterator(); i.hasNext(); ) {
     TargetType Identifier = (TargetType) i.next();
     ...
}

14.14.2. 14.14.2. The enhanced for statement 增强的 for 语句

This one is normal for loop using.这是正常的 for 循环使用。 You can declare the variable type outside the for您可以在 for 之外声明变量类型

 int i;
 for (i = 0; i < 10; i++) {}

or或者

  Integer i;
  for (i = 0; i < 10; i++) {
        System.out.println(i);
    }

the second one, if you would like to use foreach(also known as Enhanced For-loop) with the Generic type, the syntax must be:第二个,如果你想使用泛型类型的 foreach(也称为增强的 For 循环),语法必须是:

for(data_type variable : array | collection){}  

Hope this help!希望这有帮助!

As per JLS (see very bottom of 15.27.2. Lambda Body ) - in each iteration of enhanced-for loop we have a brand-new i variable => we cannot reuse ( Integer i; ) variable declared before the loop.根据JLS (参见15.27.2. Lambda Body最底部) -在增强型 for 循环的每次迭代中,我们都有一个全新的i变量=> 我们不能重用 ( Integer i; ) 在循环之前声明的变量。

We have a brand-new variable in each loop, hence we have declaration syntax here: for(Integer i : array) as it is really declared again and again on each iteration.我们在每个循环中都有一个全新的变量,因此我们在这里有声明语法: for(Integer i : array)因为它在每次迭代中一次又一次地被声明。

Proof comes from JLS code example about lambdas:证明来自关于 lambdas 的 JLS 代码示例:

void m9(String[] arr) {
    for (String s : arr) {
        foo(() -> s);
        // Legal: s is effectively final
        // (it is a new variable on each iteration)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM