Java: Out with the Old, In with the New

后端 未结 30 2029
遥遥无期
遥遥无期 2020-12-22 16:11

Java is nearing version 7. It occurs to me that there must be plenty of textbooks and training manuals kicking around that teach methods based on older versions of Java, whe

30条回答
  •  眼角桃花
    2020-12-22 16:17

    The new for-each construct to iterate over arrays and collection are the biggest for me.

    These days, when ever I see the boilerplate for loop to iterate over an array one-by-one using an index variable, it makes me want to scream:

    // AGGHHH!!!
    int[] array = new int[] {0, 1, 2, 3, 4};
    for (int i = 0; i < array.length; i++)
    {
        // Do something...
    }
    

    Replacing the above with the for construct introduced in Java 5:

    // Nice and clean.    
    int[] array = new int[] {0, 1, 2, 3, 4};
    for (int n : array)
    {
        // Do something...
    }
    

    Clean, concise, and best of all, it gives meaning to the code rather than showing how to do something.

    Clearly, the code has meaning to iterate over the collection, rather than the old for loop saying how to iterate over an array.

    Furthermore, as each element is processed independent of other elements, it may allow for future optimizations for parallel processing without having to make changes to the code. (Just speculation, of course.)

提交回复
热议问题