1

I wrote a simple retrieval for loop for array list

int[] a = new int[5] ;
for(int d:a)
{  
  Arrays.fill(a, 111);
  System.out.print(d);
}

The output of above code is 0111111111111.

I just can't figure out what is that 0 doing. My expected output is 111111111111.

When I write the same code using simple for loop

int[] a = new int[5] ;
for(int i=0;i<a.length;i++)
{  
  Arrays.fill(a, 111);
  System.out.print(a[i]);
}

it meets my expectation. I would like to know where I'm wrong.

Reporter
  • 3,897
  • 5
  • 33
  • 47

3 Answers3

0

This answer explains that in the end, for arrays, the enhanced for-each is "basically" the same as using a conventional for loop with counter.

But the essential difference is: the enhanced for loop has to pick the first array entry, to put it into the d variable, before the loop body is entered.

In your second example, no value is retrieved from the array before the array gets updated. In the first example, one value is retrieved (and later printed) before the array gets filled with 1s.

That is all there is to this.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

Check out the language spec for the description of the enhanced for loop.

For an array, it says the equivalent basic for loop is:

// This loop...
for (TargetType Identifier : Expression) {
    Statement
}

// ...is equivalent to this:
T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    {VariableModifier} TargetType Identifier = #a[#i];
    Statement
}

Substituting your first loop into this:

// T[] #a = Expression;
T[] aa = a;

// You have no labels, so no need for the L1: L2 line.

// for (int #i = 0; #i < #a.length; #i++) {
for (int i = 0; i < aa.length; ++i) {
  // {VariableModifier} TargetType Identifier = #a[#i];
  int d = aa[i];

  // Statement is your loop body:
  Arrays.fill(a, 111);
  System.out.print(d);
}

If you look at it like this, you can see that d is assigned before the Arrays.fill(a, 111); statement. As such, d isn't affected by the fill.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

First is equivalent to:

int[] a = new int[5] ;
for(int i=0; i< a.length; i++)
{  
 int d=a[i];
 Arrays.fill(a, 111);
 System.out.print(d);
}
Sergey Afinogenov
  • 2,137
  • 4
  • 13