简体   繁体   English

java:在“foreach”中计算的集合表达式的次数

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

if I do this in Java: 如果我在Java中这样做:

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

is expensiveListGeneration() invoked just once at the beggining or in every cycle iteration? 是贵的ListGeneration()在开始或每个循环迭代中只调用一次?

Is it implementation dependent? 它是依赖于实现的吗?

because it is equivalent to using an iterator, it is equivalent to calling the collections' . 因为它等同于使用迭代器,它相当于调用集合'。 iterator() method, and it is called once. iterator()方法,它被调用一次。

It's invoked once, and not implementation dependant. 它被调用一次,而不依赖于实现。 The for-each loop is based on the Iterable interface. for-each循环基于Iterable接口。 All it does is call the collection's iterator() method once at the beginning, and then works with that iterator. 它只是在开头调用集合的iterator()方法,然后使用该迭代器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM