views:

150

answers:

2

if I do this in Java:

for(String s : myCollection.expensiveListGeneration())
{
      doSomething();
}

is expensiveListGeneration() invoked just once at the beggining or in every cycle iteration?

Is it implementation dependent?

+9  A: 

because it is equivalent to using an iterator, it is equivalent to calling the collections' . iterator() method, and it is called once.

Chii
+10  A: 

It's invoked once, and not implementation dependant. The for-each loop is based on the Iterable interface. All it does is call the collection's iterator() method once at the beginning, and then works with that iterator.

Michael Borgwardt
ah, answered at the same time heh :)
Chii