0

I saw one line of code like below:

for (String w : words) sentence.add(w); // words is declared as String[] words = ...;

To my knowledge, I think that to be able to write for loop in this format, we need the 'words' being an instance of a class which implements Iterable interface and override the iterator() function. But 'words' is of type String array, how can this for loop format correct?

Can someone give me some tips please?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Bpache
  • 305
  • 2
  • 4
  • 11

3 Answers3

9

From the Java tutorial on this subject:

The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array:

// Returns the sum of the elements of a
int sum(int[] a) {
    int result = 0;
    for (int i : a)
        result += i;
    return result;
}

And from §14.14.2 of the JLS (the Java Language Specification):

The enhanced for statement has the form:

EnhancedForStatement:
    for ( FormalParameter : Expression ) Statement

The type of the Expression must be Iterable or an array type, or a compile-time error occurs.

But note that arrays don't implement Iterable; from §10.1 of the JLS:

The direct superclass of an array type is Object.

Every array type implements the interfaces Cloneable and java.io.Serializable.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • And in the Java Language Specification: http://docs.oracle.com/javase/specs/jls/se5.0/html/statements.html#14.14.2 – MrLore Mar 19 '13 at 19:51
5

As ever, the Java Language Specification is the place to look. In this case it's section 14.14.2, the enhanced for statement:

EnhancedForStatement:  
     for ( FormalParameter : Expression ) Statement

The type of the Expression must be Iterable or an array type (§10.1), or a compile-time error occurs.

...

  • If the type of Expression is a subtype of Iterable, then the translation is as follows. [... description of how iterables are handled ...]

  • Otherwise, the Expression necessarily has an array type, T[]. [... description of how arrays are handled ...]

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

Yes it is iterable in the way that you can iterate over it like any class that implements the Iterable interface, as all arrays in Java are (using the for each loop). To my knowledge, Arrays do not implement this interface, as they are just Objects, however the compiler does some magic and makes this work anyway.

Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45