Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the "condition" of a for loop called each time for Iterables?

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
}
like image 695
gsingh2011 Avatar asked Oct 07 '11 19:10

gsingh2011


People also ask

Does for loop check condition every time?

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.

What is the condition in a for loop?

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.

What happens if a condition of a loop?

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.

What is a single run of a loop called?

A single execution of the loop body is called an iteration. The loop in the example above makes three iterations.


1 Answers

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.

like image 81
Óscar López Avatar answered Sep 19 '22 19:09

Óscar López