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

后端 未结 2 1513
眼角桃花
眼角桃花 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:46

    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.

提交回复
热议问题