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

前端 未结 4 1381
走了就别回头了
走了就别回头了 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: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

提交回复
热议问题