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;
i++;
}
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?
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.
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] );
}
}
}