Can I get the list index inside for-each in java?

Asked

Viewed 1,305 times

4

When we created the for traditional we do this way:

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

Now I have this foreach:

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

In some cases, we need index. As to the for traditional, all right, it is already stated in itself. And if it is in the foreach? Can you catch the index of the list within the foreach in Java? If I declare a int i outside it, and increasing within it is a legal practice if it is not possible to recover the index, or it is better to create a for traditional?

  • You could do this using the index method if you use a List, but with an array I don’t think you can

  • 2

    @Denisrudneidesouza this has performance problems (o(n) for disordered lists), plus problems with possible repetitions (if I have 5 times the same element, I believe that indexOf return to first valid position).

1 answer

-1

I’ve done a lot of research on this and many say there’s no way.
I’ve also searched the javadoc and found nothing.
I think the solution is to either use the is normal or use a counter within the foreach itself.

int i = 0; 
for(String str : strs){
    i++;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.