3

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?

Community
  • 1
  • 1
Shiju K Babu
  • 6,389
  • 10
  • 49
  • 81

3 Answers3

3

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.

Thilo
  • 241,635
  • 91
  • 474
  • 626
  • 5
    All the gory details in [§14.14.2 of the JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2). – T.J. Crowder Aug 19 '15 at 06:19
0

No designed way to know current index in foreach loop, it works not like

 for(int i = 0; i < list.length; i++) 

but like:

Iterator<String> iter = list.iterator();
while (iter.hasNext())
Les
  • 232
  • 1
  • 4
  • 13
0

I guess you already know that any instance of a class that implements Iterable interface can be used in the foreach loop. For any finite collection of objects, there is no way an Iterator can be implemented without doing some sort of house keeping (in most cases the index). So, in effect an index is stored somewhere, though it is not accessible to us.

Have a look at the AbstractList implementation of iterator method to see how it is implemented for lists.

Dakshinamurthy Karra
  • 4,969
  • 1
  • 13
  • 25