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
Java will call genArray() once, get the iterator object, and call that multiple times.
It should only get used once - it's the same as calling this:
About the enhanced for statement, the Java Language Specifications writes:
So in your case,
genArray()
doesn't return a subtype ofIterable
but an array type, so your enhancedfor
statement is equivalent to the following basicfor
statement:And
genArray()
will thus be called only once (but the currently accepted answer is partially wrong).