2

It is common idea that I cannot iterate on some structure with forEach if this structure isn't Iterable. But why I can iterate on array in Java? Array isn't Iterable.

MyClass[] array = {new MyClass("a"), new MyClass("b")};

for (MyClass c : array) {
    System.out.println(c);
}
1
  • 3
    You can iterate over an array because the ranged-for construct works on both Iterables and Arrays. The compiler generates one style of bytecode if the argument is an Iterable, and another if it's an Array. Commented Dec 2, 2014 at 18:51

3 Answers 3

9

The reason is that the language has made an allowance for it. While it may represent the two objects differently, the sequence of iteration is the same - and the effect is transparent to you.

...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).

Sign up to request clarification or add additional context in comments.

Comments

1

The For-Each Documentation says in part The for-each construct is also applicable to arrays.

The JLS-14.4.2 The enhanced for statement says (in part),

The type of the Expression must be Iterable or an array type

Comments

1

The reason is because Java has a built in way of handling arrays in a for each loop. Check out this link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.