Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassigning array values in array of primitives does not change array

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?

like image 833
Big_Chair Avatar asked Mar 26 '26 20:03

Big_Chair


1 Answers

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...

like image 130
Fortega Avatar answered Mar 29 '26 10:03

Fortega



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!