In Java, a for-each loop.
If I have a method that generates an array, called genArray().
In the following code, will the array each time be re-generated by calling genArray()?
Or will Java call once the method and store a copy from the array?
for (String s : genArray())
{
//...
}
Thanks
The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order. Here, you do not have the option to skip any element because it does not work on an index basis. Moreover, you cannot traverse the odd or even elements only.
MAJOR BENEFIT: To sum up, the enhanced for loop offers a concise higher level syntax to loop over a list or array which improves clarity and readability.
About the enhanced for statement, the Java Language Specifications writes:
The enhanced for statement has the form:
EnhancedForStatement: for ( VariableModifiersopt Type Identifier: Expression) StatementThe Expression must either have type
Iterableor else it must be of an array type (§10.1), or a compile-time error occurs.The scope of a local variable declared in the FormalParameter part of an enhanced
forstatement (§14.14) is the contained StatementThe meaning of the enhanced
forstatement is given by translation into a basicforstatement.If the type of
Expressionis a subtype ofIterable, then letIbe the type of the expression Expression.iterator(). The enhancedforstatement is equivalent to a basicforstatement of the form:for (I #i = Expression.iterator(); #i.hasNext(); ) { VariableModifiersopt Type Identifier = #i.next(); Statement }Where
#iis a compiler-generated identifier that is distinct from any other identifiers (compiler-generated or otherwise) that are in scope (§6.3) at the point where the enhanced for statement occurs.Otherwise, the Expression necessarily has an array type,
T[]. LetL1 ... Lmbe the (possibly empty) sequence of labels immediately preceding the enhancedforstatement. Then the meaning of the enhanced for statement is given by the following basicforstatement:T[] a = Expression; L1: L2: ... Lm: for (int i = 0; i < a.length; i++) { VariableModifiersopt Type Identifier = a[i]; Statement }Where a and i are compiler-generated identifiers that are distinct from any other identifiers (compiler-generated or otherwise) that are in scope at the point where the enhanced for statement occurs.
So in your case, genArray() doesn't return a subtype of Iterable but an array type, so your enhanced for statement is equivalent to the following basic for statement:
String[] a = genArray();
...
for (int i = 0; i < a.length; i++) {
String s = a[i];
// ...
}
And genArray() will thus be called only once (but the currently accepted answer is partially wrong).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With