How does a for each loop guard against an empty list?
Solution 1
My question is how does a for each loop work for an empty list
ForEach
also works in the same way. If the length is zero then loop is never executed.
The only difference between them is use ForEach
loop when you want to iterate all the items of the list or array whereas in case of normal for
loop you can control start and end index.
Solution 2
It uses the iterator of the Iterable collection, e.g. List. It is the duty of the implementer of the Iterator to write the hasnext() method to return false if there is no next item which will be the case if the collection is empty
Solution 3
Yes, it is equivalent.
If the list is empty, the for-each cycle is not executed even once.
committedandroider
Updated on May 24, 2020Comments
-
committedandroider almost 4 years
I read on http://www.leepoint.net/notes-java/flow/loops/foreach.html. the for each equivalent to
for (int i = 0; i < arr.length; i++) { type var = arr[i]; body-of-loop }
is
for (type var : arr) { body-of-loop }
My question is how does a for each loop work for an empty list. I know for the regular for loop, the arr.length will just evaluate to 0 and the loop wont execute. What about the for each loop?
-
Eran almost 10 yearsBut the question is about an array, not a Collection.
-
ChiefTwoPencils almost 10 yearsYou can always control the end of the for-each loop with
if(something) break;
IOW, you don't have to iterate the entire contents. -
Eran almost 10 yearsHow does it answer the question? The OP knows the two code samples in the question are equivalent, and asks how the foreach loop works for an empty array, not whether it works.
-
libik almost 10 years@Eran - Second sentence is answering the question, for empty list it is not executed (it means, it works and it is not executed, you cant say more about it).
-
committedandroider almost 10 yearsI like this one but can you clarify on java docs, it says that an iterator iterates over a collection?
-
user3810043 almost 10 yearsIt is in the language specification section 14.14.2 In brief, if the collection (small c) is an array then the compiler converts the code to a standard for loop with an int counter and if the collection (small c) is an Iterable (which includes the Collection classes) then it calls the iterator.