Is Java foreach iteration order over primitives precisely defined?

后端 未结 2 1904
独厮守ぢ
独厮守ぢ 2021-02-12 05:18

Example code:

int a[] = new int[]{0, 1, 2, 3};
int result = 0;
for (int i : a)
    result += i;

Is the loop guaranteed to iterate across

相关标签:
2条回答
  • 2021-02-12 06:17

    According to the JLS, The enhanced for statement, your for-loop is equivalent to

    int[] array = a;
    for (int index = 0; index < a.length; index++) {
        int i = array[index];
        result += i;
    }
    

    "where array and index are compiler-generated identifiers that are distinct from any other identifiers (compiler-generated or otherwise) that are in scope at the point where the enhanced for statement occurs." (slightly paraphrasing the variable names here).

    So yes: the order is absolutely guaranteed.

    0 讨论(0)
  • 2021-02-12 06:18

    See section 14.14.2 of the Java Language Specification, 3rd edition.

    If the type of Expression is a subtype of Iterable, then let I be the type of the expression Expression.iterator(). The enhanced for statement is equivalent to a basic for statement of the form:

    for (I #i = Expression.iterator(); #i.hasNext(); ) {
            VariableModifiersopt Type Identifier = #i.next();
       Statement
    }
    

    Where #i is a compiler-generated identifier that is distinct from any other identifiers (compiler-generated or otherwise) that are in scope (§6.3) at the point where the enhanced for statement occurs.

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