oym
oym

Reputation: 7083

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);
}

Upvotes: 14

Views: 16231

Answers (5)

Emil
Emil

Reputation: 13789

It's better to keep an outside counter to get the index,but you could do something like this ( it's bit of an overkill for a simple task):

class Enum<T> implements Iterable<Indexer<T>> {
    private int indx;
    private Iterator<T> itr;
    private Indexer<T> indxr = new Indexer<T>();

    private Enum(Iterable<T> iter) {
        this.itr = iter.iterator();
    }

    public static <T> Enum<T> iterate(Iterable<T> iter) {
        return new Enum<T>(iter);
    }

    @Override
    public Iterator<Indexer<T>> iterator() {
        return new AbstractIterator<Indexer<T>>() {
            @Override
            protected Indexer<T> computeNext() {
                if (itr.hasNext()) {
                    indxr.index = indx++;
                    indxr.val = itr.next();
                    return indxr;
                }
                return endOfData();
            }

        };
    }

}

class Indexer<T> {
    public int index;
    public T val;

    @Override
    public String toString() {
        return String.format("[ %d : %s ]", index, val);
    }

For getting index while while iterating:

    List<Integer> list = new ArrayList<Integer>() ;
    list.addAll(Arrays.asList(1, 2, 3, 4, 5,6,55,23,12,24,16));
    for (Indexer<Integer> en : Enum.iterate(list)) 
      System.out.println(en.index+" "+en.val);

Note:The above code has dependency to Guava's AbstractIterator

Upvotes: 3

fastcodejava
fastcodejava

Reputation: 41097

There isn't way right now unless you keep a counter! I know this is ugly, but java 7 will be better. I don't know why other people are saying we don't need it. Sometimes we need to know what is last member, or odd member, etc.

Upvotes: 1

Yuval Adam
Yuval Adam

Reputation: 165242

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):
    # ....

Upvotes: 16

Justin Niessner
Justin Niessner

Reputation: 245419

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.

Upvotes: 7

Bozho
Bozho

Reputation: 597076

No. Use an outside variable.

Upvotes: 7

Related Questions