-2

Consider an ArrayList<String> list for the following examples.

I'm curious about how a for-each loop works "behind the scenes". A traditional for loop accesses elements of a list by their numerical index, like so:

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

Does the for-each syntax access the elements of the list in an essentially different way? Or is it just a shorthand version for the same thing?

For example, in the following loop, is there implicitly a variable created (like i above)? If there is, does it have a name? If not, are the elements of the list still accessed sequentially?

for(String item : list)
asteri
  • 11,402
  • 13
  • 60
  • 84
  • It uses a standard Iterator. It doesn't know that iterating a List could be done with a get(). It only uses an index lookup for arrays. – Peter Lawrey Jul 05 '13 at 22:19

3 Answers3

2

The enhanced for loop is implemented as a basic for loop using iterators.

See JLS - Section # 14.14:

The meaning of the enhanced for statement is given by translation into a basic for statement, as follows:

  • If the type of Expression is a subtype of Iterable, then the translation is as follows.

    If the type of Expression is a subtype of Iterable<X> for some type argument X, then let I be the type java.util.Iterator<X>; otherwise, let I be the raw type java.util.Iterator.

The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    VariableModifiersopt TargetType Identifier =
        (TargetType) #i.next();
    Statement
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

It uses iterator behind the scene, not the traditional index

for(String name: names){
}

is equivalent to

for (Iterator<String> i = names.iterator(); i.hasNext();){

}

Also See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
1

The enhanced for-loop is shot-hand for iterator based access to a list, not index based. It works like this:

Iterator<String> itr = list.iterator();
while(itr.hasNext()) {
  String item = itr.next():
  //your code
}
Affe
  • 47,174
  • 11
  • 83
  • 83