gsgx
gsgx

Reputation: 12249

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
}

Upvotes: 5

Views: 201

Answers (2)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236014

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.

Upvotes: 11

Varun Achar
Varun Achar

Reputation: 15109

Nope it doesn't. It keeps the iterable item it receives from the getIterable() in memory and uses that reference. Quick way to check is to put a break point at the for statement and debug your way in to the JDK. You'll come to know.

Upvotes: 3

Related Questions