Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to the iteration number in Java's foreach

How can you refer to the index of an array in the foreach?

My code

String[] name = { "hello", "world" };
for ( int k : name[k] ) {
   --- cut ---
}

I expecting that the foreach -loop will

1. set k = 0 in first iteration so that name[0] works correctly
2. set k = 1 in the next iteration...

I get the error message

foreach not applicable to expression type

like image 364
Léo Léopold Hertz 준영 Avatar asked Nov 29 '22 12:11

Léo Léopold Hertz 준영


1 Answers

That's because the index is not available when using the foreach syntax. You have to use traditional iteration if you need the index:

for (int i =0; i < names.length; i++) {
   String name = names[i];
}

If you do not need the index, the standard foreach will suffice:

for (String name : names) {
    //...
} 

EDIT: obviously you can get the index using a counter, but then you have a variable available outside the scope of the loop, which I think is undesirable

like image 106
oxbow_lakes Avatar answered Dec 05 '22 10:12

oxbow_lakes