I know it's not possible to get the index in foreach loop. Either we need to use normal loop or use an index which gets incremented/decremented in each iteration.
I have followed this question also. Java, How do I get current index/key in “for each” loop.
I just want to know whether, Java keeps any index in each iteration. If so, how?
Depends.
There are two versions of this loop, for arrays and for Iterable (things like List).
For arrays, the compiler will create a "normal" for (int i=0; i<arr.length; i++) loop. So here you have that index.
For Iterable, it becomes while(iter.hasMore()){. So there is no index in the loop itself. Depending on the Iterable implementation, there may still be one inside the Iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With