I try to set the values of a 2D boolean array with 2 loops like this:
boolean[][] frame = new boolean[10][4];
for (boolean[] column : frame)
for (boolean b : column)
b = true;
But that doesnt seem to work, all booleans remain false, why?
You cannot assign new values to objects in an array, because the original object will not be changed. Following code will do the trick.
boolean[][] frame = new boolean[10][4];
for (boolean[] column : frame)
for (int i = 0; i < column.length; i++)
column[i] = true;
A bit more explanation:
The array contains elements which point to booleans. When you assign the value of one of the elements of the array to a variable called b (for (boolean b : column)), the variable b points to the same object the element in the array points to. Next, you point the variable b to true. Now, b will be true. However, the element in the array still points to the same object.
I hope this is clear now. An image would make it more understandable...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With