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

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

Leave a Comment