Home >Java >javaTutorial >How to Track Iteration Count in Java\'s For-Each Loop?

How to Track Iteration Count in Java\'s For-Each Loop?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 01:36:02463browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn