why is the enhanced for loop more efficient than the normal for loop

后端 未结 7 1777
一整个雨季
一整个雨季 2020-12-01 00:35

I read that the enhanced for loop is more efficient than the normal for loop here:

http://developer.android.com/guide/practices/performance.html#fo

7条回答
  •  忘掉有多难
    2020-12-01 00:54

    all answers are good,and I think no more answers are needed, but I just want to point out that:

    The enhanced for statement can be used only to obtain array elements

    it cannot be used to modify elements.

    If your program needs to modify elements, use the traditional counter-controlled for statement.

    take a look

    int[] array = { 1, 2, 3, 4, 5 };
    for (int counter = 0; counter < array.length; counter++)
        array[counter] *= 2;
    

    We could not use the enhanced for statement because we’re modifying the array’s elements.

提交回复
热议问题