java: how many times is the collection expression evaluated in a “foreach”

后端 未结 2 1549
眼角桃花
眼角桃花 2021-01-17 07:10

if I do this in Java:

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

is expensiveListGeneration() invoked

2条回答
  •  日久生厌
    2021-01-17 07:42

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

提交回复
热议问题