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

无人久伴 提交于 2019-12-31 17:51:13

问题


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?


回答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.




回答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




回答3:


Yes, it is equivalent.

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




回答4:


As @user3810043 alludes to in their answer comments, the enhanced for statement is literally evaluated the same as an equivalent basic for statement:

14.14.2. The enhanced for statement

...

The type of the Expression must be a subtype of the raw type Iterable or an array type (§10.1), or a compile-time error occurs.

...

Otherwise, the Expression necessarily has an array type, T[].

Let L1 ... Lm be the (possibly empty) sequence of labels immediately preceding the enhanced for statement.

The enhanced for statement is equivalent to a basic for statement of the form:

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    {VariableModifier} TargetType Identifier = #a[#i];
    Statement
}

#a and #i are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

^ Quote from The Java® Language Specification



来源:https://stackoverflow.com/questions/24845281/how-does-a-for-each-loop-guard-against-an-empty-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!