Lets say I have the following code:
for (Object obj : Node.getIterable()) {
//Do something to object here
}
and Node.getIterable() returns an iterable. Does the getIterable() function get called every time or only when the for loop is started? Should I change it to:
Iterable<Object> iterable = new Iterable<Object>();
//populate iterable with objects
for (Object obj : iterable) {
//Do something
}
Syntax. The for loop consists of three optional expressions, followed by a code block: initialization - This expression runs before the execution of the first loop, and is usually used to create a counter. condition - This expression is checked each time before the loop runs.
Condition is an expression that is tested each time the loop repeats. As long as condition is true, the loop keeps running. Increment is an expression that determines how the loop control variable is incremented each time the loop repeats successfully (that is, each time condition is evaluated to be true). Example.
The condition is tested at the beginning of each iteration of the loop. If the condition is true ( non-zero ), then the body of the loop is executed next. If the condition is false ( zero ), then the body is not executed, and execution continues with the code following the loop.
A single execution of the loop body is called an iteration. The loop in the example above makes three iterations.
The Java Language Specification details exactly what the foreach statement does. See "14.14.2 The enhanced for statement" for more information (http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2). But in short, in fact the language does guarantee that the expression you're iterating over will only be evaluated once.
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