Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.
Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?
As an example where this might be needed, consider(this is from actual production code):
int i = 1;
for (final String action : actions) {
parameters.set(String.valueOf(i++), action);
}
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.
For a low number of iterations (100-1000), the enhanced for loop seems to be much faster with and without JIT. On the contrary with a high number of iterations (100000000), the traditional loop is much faster.
Difference between for loop and advanced for loop in Java 2) The enhanced for loop executes in sequence. i.e the counter is always increased by one, whereas in for loop you can change the step as per your wish e.g doing something like i=i+2; to loop every second element in an array or collection.
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse a collection of elements including arrays.
Why would they need to provide yet another way of accessing elements by index?
The enhanced for loop was created as a shortcut for when you don't need the index of the element. It streamlined things.
If you still need the index, fall back to a regular for loop. That's one of the reasons they're there.
Well, like you said, if you must have an index just use a standard for
loop, or update a counter manually.
But rethink your question. Why should you need an index in a for (Object o : list)
loop?
The whole point of using an enhanced loop is to abstract away the nasty parts of using an index or an iterator.
Most languages today do not give this kind of functionality in loops. Just as an example, the Pythonic way to do this is:
for index, val in enumerate(someList):
# ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With