简体   繁体   中英

Repeat iteration in enhanced-for loop

Regular for-loop

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

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

    // ...
}

Enhanced for-loop

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

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

    // ...
}

Is there any way to repeat an iteration of an enhanced for-loop? 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:

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.)

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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