0

Say I have a dataObject, who has a getChildren() function which returns a collection, but for whatever reason is a slow process that I want to avoid. I then want to iterate over said collection. For the sake of this getChildren() will return an empty collection when it has no children, not null.

Can I get away with doing:

for(dataObject child : parent.getChildren()){ ... }

or is that going to call getChildren() each loop, meaning that to avoid that costly call each time, I need to instead do:

Collection<dataObject> children = parent.getChildren();
for(dataObject child : children){ ... }

This could also cause problems if I the parent returns a different collection, for instance if a child was added/removed, and I was wanting to look at a snapshot of the children at that moment (let's gloss over other issues with that).

I suspect that the first version is indeed fine, as the for loop would get an iterator for the collection when it starts and just refer to that iterator, but it's something I've never confirmed.

thecoshman
  • 8,394
  • 8
  • 55
  • 77

1 Answers1

3

From the JLS:

The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    {VariableModifier} TargetType Identifier =
        (TargetType) #i.next();
    Statement
}

so it only evaluates the Iterable once.

user2357112
  • 260,549
  • 28
  • 431
  • 505