Arrays and enhanced for loops?

后端 未结 6 503
闹比i
闹比i 2021-01-22 15:19

Can someone please explain what is going on in this method?

class test{  
public static void main(String args[])
{
   int[] x = new int[4]; 
   int[] xy = new i         


        
6条回答
  •  感情败类
    2021-01-22 15:27

    It should be straight-forward to find out, if you trace through using debugger.

    In brief, it is getting each value in x, and use the value as index to increment corresponding value in xy.

    It will be more obvious if you initialize both array with meaningful values:

    int[] x = {1,1,3,3}
    int[] xy = new int[4]; // initialized to 0 by default
    

    after your piece of code, you will find xy containing {0,2,0,2}.


    You should understand how enhanced-for-loop is expanded for array:

    for (T v : arr) {
        // do something 
    }
    

    is transformed to

    for (int i = 0; i < arr.length; ++i) {
        T v = arr[i];
        // do something 
    }
    

    Obviously your understanding on how enhanced for loop being expanded is wrong.

提交回复
热议问题