If there is a method call MyClass.returnArray()
and I iterate over the array using the for-each construct (also called the "enhanced for" loop):
for (ArrayElement e : MyClass.returnArray()) { //do something }
will then the returnArray()
method be called for every iteration?
A for-each loop is a loop that can only be used on a collection of items. It will loop through the collection and each time through the loop it will use the next item from the collection. It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array.
The forEach() method provides several advantages over the traditional for loop e.g. you can execute it in parallel by just using a parallel Stream instead of a regular stream. Since you are operating on stream, it also allows you to filter and map elements.
for-each is an advanced looping construct. Internally it creates an Iterator and iterates over the Collection.
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.
No, it won't. The result of the first call will be stored in the compiled code in a temporary variable.
From Effective Java 2nd. Ed., Item 46:
Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once.
From the java language spec:
EnhancedForStatement: for ( VariableModifiersopt Type Identifier: Expression) Statement
and later on:
T[] a = Expression; L1: L2: ... Lm: for (int i = 0; i < a.length; i++) { VariableModifiersopt Type Identifier = a[i]; Statement }
This is (in pseudo code) the equivalent of the advanced for loop for arrays. And it is made clear, that the Expression is evaluated once and the resulting array is assigned to T[] a
.
So it's perfectly safe to use even complex expressions in the advanced for loop statement.
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