开发者

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

This question already has answers here: Why does the foreach statement not change the element value? (6 answers) 开发者_如何学运维 Closed 5 years ago.

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?


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


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


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.


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.


In your case, you cannot. For-each hides the iterator on the underlying collection, so here you cannot figure out what position in "numbers" you currently are in when you try "initializing" the array. This is one use case the "advanced" loop isn't made for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜