Enhanced for loop weirdness

This could be do to inexperience with Java on my part... but I can't seem to make any sense out of this:

class ForTest{

publicstaticvoid main(String[] args){

boolean[] arr =newboolean[10];

for (int i = 0; i < 5; i++){

arr[(int)(Math.random()*10)] =true;

}

System.out.println("--Pre--");

for (boolean b : arr){

System.out.println(b);

}

// reset back to false?

for (boolean b : arr){

b =false;

}

System.out.println("--Post--");

for (boolean b : arr){

System.out.println(b);

}

}

}

sample output:

--Pre--

true

false

false

true

false

false

false

true

true

true

--Post--

true

false

false

true

false

false

false

true

true

true

Can anyone explain what is going on?

[1930 byte] By [ErikSilkensena] at [2007-11-26 16:27:00]
# 1

Enhanced for loops are read only.

You cannot use them to modify arrays or collections.

Under the hood this:for (boolean b : arr)

b = false;

Translates to:for (int i = 0; i < arr.length; i++) {

boolean b = arr[i];

b = false;

}

Which clearly does nothing useful.

Use the standard for loop instead.

Regards.

jfbrierea at 2007-7-8 22:51:10 > top of Java-index,Java Essentials,New To Java...
# 2

In the middle loop, you're not setting anything other than the temporary variable. You first set the temp variable b to the value in the array, and then you set it to false (thus making the loop pointless). So nothing changes.

I think it would be as if you ran this loop:

for (int i = 0; i < arr.length; i++) {

boolean b = arr[i];

b = false;

}

paulcwa at 2007-7-8 22:51:10 > top of Java-index,Java Essentials,New To Java...
# 3
Oh... thanks! It makes sense now...
ErikSilkensena at 2007-7-8 22:51:10 > top of Java-index,Java Essentials,New To Java...
# 4
I hate it when I'm too slow and turn into an echo.
paulcwa at 2007-7-8 22:51:10 > top of Java-index,Java Essentials,New To Java...
# 5

for (boolean b : arr) {

b = false;

}

should be understood asboolean[] a = arr;

for(int i = 0; i < a.length; i++) {

boolean b = a[i];

b = false;

}

As explained in the second example in [url http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2]The JLS (14.14.2)[/url]

It should be clear from this "translation" why the array elements aren't altered

by the assignment b=false.

[Edit]D@mn. Shouldn't have spent so long trying to format the link...

Message was edited by:

pbrockway2

pbrockway2a at 2007-7-8 22:51:10 > top of Java-index,Java Essentials,New To Java...