36

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?

1

2 Answers 2

49

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

32

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.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.