Generic for-loop: is there any way to get iteration information?

I use to implement loops with such generics:

for (final Dog lDog : lAllDog) {
   ...
}

Misfortune for another business case. I need the current number of iterations. I know I can solve this by encoding something like this:

for (int i = 0 ; i < lAllDog.length(); i++) {
   System.out.println(i);
}

or

int i = 0;
for (final Dog lDog : lAllDog) {
   ...
   i++;
}

but is there a way to get the current number of iterations with my first code example without declaring a new one intor changing the whole title of the loop?

thanks a lot

+5
source share
5 answers

In short, no. To do this, you need to use the indexing method.

+5
source

No, there is no other way to get an iteration counter except as described in your question. You will have to use the old counter method.

+1

. for . , .

, Iterable . , .

+1

Not if your list has unique elements

Maybe you can try this

for (final Dog lDog : lAllDog) {

 int i=  lAllDog.indexOf(lDog);
}
+1
source

They say that every problem in computer science can be solved in a more indirect way.

class Indexed<T>
    int index;
    T value;

static <T> Iterable<Indexed<T>> indexed(Iterable<T> iterable){ ... }

for(Indexed<Dog> idog : indexed(dogs))
    print(idog.index);
    print(idog.value);

In java 8, we probably want to cancel this control pattern as

forEach(dogs, (index, dog)->{ 
    print(index);
    print(dog);
});

static <T> void forEach(Iterable<T> collections, Acceptor<T> acceptor){...}

interface Acceptor<T>
    void accept(int index, T value);
+1
source

All Articles