Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JVM keeps track of index in foreach loop in Java? If so, How?

Tags:

java

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?

like image 942
Shiju K Babu Avatar asked Nov 27 '25 20:11

Shiju K Babu


1 Answers

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.

like image 125
Thilo Avatar answered Nov 29 '25 09:11

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!