简体   繁体   中英

Generic for-loop: Is there a way to get iteration information?

I am used to implement loops with generics like that:

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

Unfortunality for another business case I need the current count of the iteration. I know I can solve this by coding somthing like that:

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 count of iteration with my first code example without declaring a new int or change the whole loop header?

Thx a lot

Briefly, no. You have to use the indexing method to do that.

No, there is no other to get count of iteration other than you described in your question. You'll have to use old way to have counter defined

No. The enhanced for loop doesn't hold an index. You'll have to introduce it yourself if you want one.

The reason is because it's based on Iterable interface. Essentially, it uses an iterator to loop through a collection.

No, if your list has unique elements

May be you can try this

for (final Dog lDog : lAllDog) {

 int i=  lAllDog.indexOf(lDog);
}

They say every problem in computer science can be solved by more indirection

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM