Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a for each loop guard against an empty list?

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?

like image 254
committedandroider Avatar asked Jul 19 '14 21:07

committedandroider


People also ask

Does forEach work on empty list?

Yes, it is equivalent. If the list is empty, the for-each cycle is not executed even once.

What happens if you try to loop through an empty list Python?

And yes, you can loop over an empty list, but there will be 0 iterations.

Does forEach handle null Java?

Below are some important points about the Java 8 forEach loop while we are using it to iterate over a map. If the map's key is containing null then forEach loop will print null. If we do not want to print the null value then we can add a simple null check like below.

How do you use each loop in a list?

Only use the for-each loop when you want to loop through all the values in an array or list. If you only want to loop through part of an array or list use a for loop instead. Also use a for loop instead of a for-each loop if you want to change any of the values in the array or list.


2 Answers

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.

like image 148
Braj Avatar answered Oct 02 '22 14:10

Braj


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

like image 23
user3810043 Avatar answered Oct 02 '22 14:10

user3810043