bachtick
bachtick

Reputation: 59

Is there a way to go back by one iteration in a for-each loop?

For example, if I were to do...

for (String s : arraylist) {
    // Do something with string
}

If it isn't possible, is there another method of traversing through some sort of collection class while controlling the iteration counter? I tried looking through the answers to this question but couldn't think of a way that was clear to me.

Any suggestions are appreciated!

Upvotes: 1

Views: 1338

Answers (3)

Most Noble Rabbit
Most Noble Rabbit

Reputation: 2776

It depends on what you are trying to do, but you can use a while-loop and increment the index when it's appropriate:

while(i<limit){
   list.get(i);
   // Do something

   if(someConditionMet){
     i++
   }
}

Or you can use a for-loop without incrementing the index after each iteration:

for (int i = 0; i < 5; ) {
   list.get(i);
   // Do something

    if(someConditionMet){
        i++;
    }
}

Also if the collection implements Iterable, you can use the iterator to iterate over the collection:

List<Integer> list;

Iterator<Integer> iterator = list.iterator();

while(someCondition){
    if(someOtherContion){
        Integer next = iterator.next();
    }
}

Upvotes: 2

Naman Shah
Naman Shah

Reputation: 1

Don't use a For Each Element In Collection at all.

Make a loop declaring your own iterator starting from 0 till collection Count property value and using a Compare Number component as a condition tester.

The current item in collection can be accessed using explicite iterator value (Get Item By Index) and relative items by using additional fixed offset.

Upvotes: 0

Ivonet
Ivonet

Reputation: 2731

You can manipulate the i in the loop... it is not advisable but it can be done :-)

for (int i = 0; i < list.size(); i++) {
      Object o =  list.get(i);
      if (aCondition) {
        i--; //or somthing
      }
}

Upvotes: 1

Related Questions