简体   繁体   English

在增强型for循环中重复迭代

[英]Repeat iteration in enhanced-for loop

Regular for-loop 定期循环

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

    if (iWantToRepeat) {
        i--;
        continue;
    }

    // ...
}

Enhanced for-loop 增强了for循环

for (Foo f : Bar) {
    // ...

    if (iWantToRepeat) {
        // What can I put here?
    }

    // ...
}

Is there any way to repeat an iteration of an enhanced for-loop? 有没有办法重复增强的for循环的迭代? I get the feeling there might be because it's based on iterators and if I had access to them I could do it I think. 我感觉可能有,因为它基于迭代器,如果我可以访问它们,我想我可以做到。

No, you can't. 不,你不能。 In every iteration the Iterator procedes by 1 step. 在每次迭代中, 迭代器都会前进一步。 However you can use a do-while loop to get the same effect: 但是,您可以使用do-while循环来获得相同的效果:

for (Foo f : Bar) {
    boolean iWantToRepeat;
    do {
        // ...
        iWantToRepeat = //...;
        // ...
    } while(iWantToRepeat);
}

No, you cannot repeat an element going back in the loop. 不,你不能重复循环中的元素。 The only solution is adding a new loop inside the enhanced for. 唯一的解决方案是在增强版中添加一个新循环。 In my opinion this should be the way to do that even in a classic for, going forth and back is not very clean and can be harder to understand when reviewing the code. 在我看来,这应该是即使在经典中也是如此,前后不是很干净,在查看代码时可能更难理解。

for (Foo f: bar) {
   boolean notEnough=false;
   do {
      ... //this code will be always executed once, at least
     // change notEnough to true if you want to repeat
   } while (notEnough);
}

or 要么

for (Foo f: bar) {
   boolean notEnough=chooseIfYouWantToRunIt();
   while(notEnough) {
      ... //this code can be not executed for a given element

   } 
}

You should view the enhanced for loop as purely a shortcut for the 95% of times you just need to iterate through something, without doing anything "unusual" that it doesn't support (modifying what you're iterating through, iterating through some elements more than once, etc.) 你应该将增强的for循环看作纯粹的快捷方式,只需95%的时间你只需要迭代一些东西,而不做任何它不支持的“异常”(修改你正在迭代的东西,迭代一些元素)不止一次,等等)

However, if your use case falls into one of the above categories, you'll just have to fall back to using the standard for loop (it's hardly that much more code to write, after all, and is certainly much better than hacking around a for each loop to get the same result.) 但是,如果你的用例属于上述类别之一,那么你只需要回到使用标准for循环(毕竟,编写的代码几乎没有那么多,并且肯定比黑客攻击更好。为每个循环获得相同的结果。)

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

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