Indexing for (datatype element : array) loops

Hi @RFullum

The for-each loop that not provide a counter by itself, 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).

So, the solution is to either have your own counter, like:

int index = 0;
for(Ball ball : balls) {
    System.out.println("Current index is: " + (index++));
}

or make the class possess the id.

Best regards

2 Likes