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

22,352

Solution 1

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.
}

Solution 2

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).

Solution 3

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.

Solution 4

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.

Share:
22,352
Corleone
Author by

Corleone

Updated on July 09, 2022

Comments

  • Corleone
    Corleone almost 2 years

    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?

  • nishu
    nishu about 14 years
    also use int[] instead of Integer[] unless required!