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

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 I = counter++; // Assigns to i. Does not assign to the array.

}.

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 Does not assign to the array. }.

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 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 ){ numberscounter = 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 Length; i++){ numbersi = i; } Note, it is possible to fill all elements with the same value using Arrays.

Fill(int array, int val).

Also use int instead of Integer unless required! – Nishu Apr 1 '10 at 0:33.

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.

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: java.sun.com/j2se/1.5.0/docs/guide/langu... Take a look at the last paragraph.

The reason why you get null values as output is that you do not store any values in the array. Clearly, this is not the intended use case for the foreach loop. Note, it is possible to fill all elements with the same value using Arrays.

Fill(int array, int val).

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions