2

Consider the following simple code

    String[] strArray = new String[10];
    for(String s : strArray) {
        System.out.println(s);
    }

As far as I know for-each construct like for(String s : strArray) uses an Iterator internally to iterate over the elements. Is is the same case while iterating over Array?

If yes then why can't we do the following

Iterable<String> strIterator = strArray.iterator();//illegal
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289

2 Answers2

2

As far as I know for-each construct like for(String s : strArray) uses an Iterator internally to iterate over the elements.

Well it does when strArray is an iterable - it just works differently for arrays.

All the details are in section 14.14.2 of the JLS. In particular:

Otherwise, the Expression necessarily has an array type, T[].

Let L1 ... Lm be the (possibly empty) sequence of labels immediately preceding the enhanced for statement.

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

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
   VariableModifiersopt TargetType Identifier = #a[#i];
   Statement
}

#a and #i are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

TargetType is the type of the loop variable as denoted by the Type that appears in the FormalParameter followed by any bracket pairs that follow the Identifier in the FormalParameter (§10.2).

In other words - when you're iterating over an array, it just uses the length field as if you wrote it out by hand.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

It simply uses a forloop on all arrays, but Iterator as you say on all things iterable..

its a convenient JLS quirk

Niels Bech Nielsen
  • 4,777
  • 1
  • 21
  • 44