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
}
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.