How does primitive array work with new for each loop in Java?

后端 未结 7 745
粉色の甜心
粉色の甜心 2020-12-02 01:41

I understand that new for each loop works with Iterable and arrays, but I don\'t know what goes behind the scenes when working with arrays.

Can anyone help me under

7条回答
  •  余生分开走
    2020-12-02 02:07

    This is the equivalent to:

    final int len = number.length;
    for(int j = 0; j < len; j++) {
      int i = number[j];
    }
    

    Note that the forEach will not evaluate the .length in each loop. This might be also be eliminated by the JVM, but especially in case of collections, where some would use

    for(int j = 0; j < collection.size(); j++) {
    

    it makes a (small) difference to the faster

    int len = collection.size()
    for(int j = 0; j < len; j++) {
    

提交回复
热议问题