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?
Yes, it is equivalent. If the list is empty, the for-each cycle is not executed even once.
And yes, you can loop over an empty list, but there will be 0 iterations.
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.
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.
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.
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
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