Java 1.5 For Loop – get iteration number


I am trying to improve my for loops and was curious if there is a better way to get the iteration number.

Here is an example:

int i = 0;
String stringArray[] = new String[ getCollection.size() ];

for( String value : getCollection() ) {
     stringArray[ i ] = value;

Using the Java 5 for loop I do not need to instantiate an iterator. Instead, the for loop does this for me. In my example, I am trying to add items to a string array. In order to do this, I have to provide an index for where to place the data in the string array. Is there a way of getting the iteration number of the for loop without having to manually keep track of it using the int i like I have showed?

Thanks in advance for your time.

JDK5 has introduces a pretty good set of features like: -

New Collections Classes
Enhanced for Loop

check out this to get what all features are there in JDK5

The enhanced for loop is intended to be used for Collections that have Iterators, as you want to also access an Array during the same loop, you have no choice but to manually maintain your (lowercase) iterator.

You can, however, eliminate one line from your code, like so:
stringArray[ i++ ] = value;

(choosing pre-increment (++i) or post-increment (i++) is not just a matter of style)

Even the classic for loop would need some extra effort to do this task, as you cannot declare multiple iterators of different types.

Others already said about the i++ and next() of iterator inside for loop.

But if you really just want to convert from Collection to array, you could use something like:

String stringArray[] = getCollection.toArray(new String[0])

Thank you for the feedback. If one was to do this:

stringArray[ i++ ] = value

The i value would need to start at -1 since the increment occurs first, then the string array value is inserted, correct?

Maybe the one line command suggested by krzyk is the best approach.

If you want an Array from your Collection, then, yes.

The answer to your -1 question is: no.

What I hinted at with “choosing pre-increment (++i) or post-increment (i++) is not just a matter of style” is this: ++i says “increment i and use the resulting value”, i++ says “use the value of i, then increment”.

If you compile and run the following contrived code, you’ll see that it gives output that fits the above description.

public class IncrementTest {
  public static void main( String[] args ) {
    int[] array = new int[3];
    int index = 0;
    array[index++] = 1;
    array[++index] = 2;
    for( int i = 0; i < array.length; ++i ) {
      System.out.println( array[i] );

Thank you for explaining the difference to me. After re-reading your post, I should have picked up on that. Thanks again.