Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an array in Java using the 'advanced' for each loop [duplicate]

Is it possible to initialise an array in Java using the 'advanced' for loop?

e.g.

    Integer[ ] numbers = new Integer[20];
    int counter = 0;
    for ( Integer i : numbers )
    {
        i = counter++;
    }

    for ( Integer i : numbers )
    {
        System.out.println(i);
    }

This prints all nulls, why is that?

like image 803
Corleone Avatar asked Mar 31 '10 21:03

Corleone


4 Answers

No, because you aren't assigning to the array, you are assigning to the temporary variable called i. The array doesn't see the change.

The following shows roughly equivalent code using the normal for loop. This should make it easier to see why it fails to update the array:

for (int j = 0; j < numbers.length; j++) { 
    Integer i = arr[j]; // i is null here.
    i = counter++; // Assigns to i. Does not assign to the array.
}
like image 96
Mark Byers Avatar answered Nov 13 '22 20:11

Mark Byers


The reason why you get null values as output is that you do not store any values in the array.

You can use the foreach loop to initialize the array, but then you must manually maintain a counter to reference the array elements:

for (Integer i : numbers ){
    numbers[counter] = counter;
    counter++;
}

Clearly, this is not the intended use case for the foreach loop. To solve your problem, I would suggest using the "traditional" for loop:

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

Note, it is possible to fill all elements with the same value using Arrays.fill(int[] array, int val).

like image 39
matsev Avatar answered Nov 13 '22 20:11

matsev


Basically no, not as you wish. In the 'advanced' for loop, there is no way to access the hidden counter, and neither is there to perform a write access on the corresponding array slot.

like image 2
Thomas Pornin Avatar answered Nov 13 '22 19:11

Thomas Pornin


The 'advanced' for-loop doesn't expose the counter to you, and hence, you cannot write the result of counter++ to the specific array slot.

Your case is the case where the 'advanced' for-loop isn't made for. See:

http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html

Take a look at the last paragraph.

like image 1
ryanprayogo Avatar answered Nov 13 '22 20:11

ryanprayogo