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?
The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection. The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
As it turned out, FOREACH is faster on arrays than FOR with length chasing. On list structures, FOREACH is slower than FOR. The code looks better when using FOREACH, and modern processors allow using it. However, if you need to highly optimize your codebase, it is better to use FOR.
Yes. The foreach loop will iterate through the list in the order provided by the iterator() method.
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.
because it is equivalent to using an iterator, it is equivalent to calling the collections' . iterator() method, and it is called once.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With