Java – way to access an iteration-counter in Java’s for-each loop

for-loopforeachjavaloops

Is there a way in Java's for-each loop

for(String s : stringArray) {
  doSomethingWith(s);
}

to find out how often the loop has already been processed?

Aside from using the old and well-known for(int i=0; i < boundary; i++) – loop, is the construct

int i = 0;
for(String s : stringArray) {
  doSomethingWith(s);
  i++;
}

the only way to have such a counter available in a for-each loop?

Best Answer

No, but you can provide your own counter.

The reason for this is that the for-each loop internally does not have a counter; it is based on the Iterable interface, i.e. it uses an Iterator to loop through the "collection" - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).