Does Java's for-each call an embedded method (that returns the collection) for every iteration?

前端 未结 4 1144
借酒劲吻你
借酒劲吻你 2021-02-03 20:41

If there is a method call MyClass.returnArray() and I iterate over the array using the for-each construct (also called the \"enhanced for\" loop):

f         


        
4条回答
  •  粉色の甜心
    2021-02-03 21:15

    From the java language spec:

    EnhancedForStatement:
        for ( VariableModifiersopt Type Identifier: Expression) Statement
    

    and later on:

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

    This is (in pseudo code) the equivalent of the advanced for loop for arrays. And it is made clear, that the Expression is evaluated once and the resulting array is assigned to T[] a.

    So it's perfectly safe to use even complex expressions in the advanced for loop statement.

提交回复
热议问题