Reputation: 12523
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
Upvotes: 5
Views: 1393
Reputation: 19682
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);
Upvotes: 1
Reputation: 20155
No, if your list has unique elements
May be you can try this
for (final Dog lDog : lAllDog) {
int i= lAllDog.indexOf(lDog);
}
Upvotes: 1
Reputation: 3331
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.
Upvotes: 1
Reputation: 4551
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
Upvotes: 1
Reputation: 272297
Briefly, no. You have to use the indexing method to do that.
Upvotes: 5