1

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!

bachtick
  • 49
  • 6
  • 1
    No, it's not possible with a for-each loop. You need to create an indexed for loop or a while loop. – Ted Klein Bergman May 20 '21 at 16:36
  • A `ListIterator` does have "previous" functionality. Since it appears (by naming) `arrayList` is a `List` then consider using the `arrayList.listIterator()`. –  May 20 '21 at 16:44

3 Answers3

2

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();
    }
}
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12
0

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
      }
}
Ivonet
  • 2,492
  • 2
  • 15
  • 28
0

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.