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