开发者

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
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜