Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

loops

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

like image 459
s_bei Avatar asked Mar 18 '13 16:03

s_bei


2 Answers

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

like image 92
Brian Agnew Avatar answered Oct 06 '22 00:10

Brian Agnew


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

like image 22
Charu Khurana Avatar answered Oct 06 '22 00:10

Charu Khurana