Home >Java >javaTutorial >How to Track Iteration Count in Java\'s For-Each Loop?
Accessing Iteration Index in Java's For-Each Loop
In Java's for-each loop, accessing the current iteration count can prove to be a bit challenging. Unlike the traditional for loop (e.g., for (int i = 0; i < array.length; i )), the for-each loop (e.g., for (String s: stringArray) does not provide an iteration counter.
Is there a built-in way?
Unfortunately, there is no built-in way to access an iteration count directly with the for-each loop construct.
Alternative Approach: Counter Variable
The only way to keep track of iteration count in a for-each loop is to manually define a counter variable and increment it within the loop. For example:
<code class="java">int counter = 0; for (String s: stringArray) { // Do something with s counter++; }</code>
This approach allows you to keep track of the current iteration and use it for various purposes, such as displaying progress or limiting the number of iterations.
The above is the detailed content of How to Track Iteration Count in Java\'s For-Each Loop?. For more information, please follow other related articles on the PHP Chinese website!