Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enhanced enhanced for loop

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);
}
like image 935
oym Avatar asked Nov 29 '10 21:11

oym


People also ask

What is an enhanced for loop in Java?

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.

Is enhanced for loop faster Java?

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.

What is the difference between for loop and enhanced for loop in Java?

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.

When would you use an enhanced for loop?

As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse a collection of elements including arrays.


2 Answers

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.

like image 168
Justin Niessner Avatar answered Sep 18 '22 16:09

Justin Niessner


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):
    # ....
like image 41
Yuval Adam Avatar answered Sep 18 '22 16:09

Yuval Adam