Can you get the index of the list inside the for-each in java? [duplicate]

5

When we create the traditional for we do it like this:

for(int i = 0; i<strs.lenght; i++){
     Log.wtf(TAG, "Jon Snow is "+strs[i]);
}

Now I have the following for each :

for(String str: strs){
    Log.wtf(TAG, "Jon Snow is "+str);
}

In some cases, we require index . As for traditional for , that's fine, it's already declared in itself. What if it is in for each ? Can you get the index from the list within for each in Java? If I declare a int i off of it, and increment in is legal practice if it is not possible to retrieve index , or is it better to create a for traditional?

    
asked by anonymous 24.06.2017 / 06:13

1 answer

0

I've done a lot of research on this and many say it has no way. I've also researched the javadoc and found nothing. I think the solution is either to use normal for or use a counter inside the foreach itself.

int i = 0; 
for(String str : strs){
    i++;
}
    
24.06.2017 / 06:32