Kosi2801 Kosi2801 - 10 months ago 41
Java Question

Is there a way to access an iteration-counter in Java's for-each loop?

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

for(String s : stringArray) {

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

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

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

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

Answer Source

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