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

前端 未结 4 1364
走了就别回头了
走了就别回头了 2021-02-05 02:17

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[         


        
相关标签:
4条回答
  • 2021-02-05 02:23

    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.

    0 讨论(0)
  • 2021-02-05 02:32

    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

    0 讨论(0)
  • 2021-02-05 02:34

    Yes, it is equivalent.

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

    0 讨论(0)
  • 2021-02-05 02:46

    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

    0 讨论(0)
提交回复
热议问题