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

后端 未结 7 705
粉色の甜心
粉色の甜心 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:01

    The loop is equivalent to:

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

    where j is an internally generated reference that does not conflict with normal user identifiers.

    0 讨论(0)
  • 2020-12-02 02:02

    IntStream.range(1,4) can be used, if using java 8.

    0 讨论(0)
  • 2020-12-02 02:04

    In your code, you allocate an array of 10 integers in the memory and obtain a reference to it. In the for-loop you simply iterate over every item in the array, which initially will be 0 for all the items. The value of every item will be stored in the variable i declared in your for-loop as you iterate the array elements.

    0 讨论(0)
  • 2020-12-02 02:04

    The for each over arrays is essentially "sugar" over this construct:

    for(int i = 0;i<number.length;i++)
    {  
    }
    

    I would imagine this was provided as a construct of the language so that people could use the enhanced for loop over a structure that was iterated over in the old way.

    0 讨论(0)
  • 2020-12-02 02:05

    this is equivalent to:

    for(int x = 0; x < number.length; x++) {
      int i = number[x];
    }
    
    0 讨论(0)
  • 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++) {
    
    0 讨论(0)
提交回复
热议问题