Bpache Bpache - 3 months ago 7x
Java Question

Enhanced for loop with array

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?


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:

    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.