Fraser Price
Fraser Price

Reputation: 909

Setting all values in a boolean array to true

Is there a method in Java for setting all values in a boolean array to true?

Obviously I could do this with a for loop, but if I have (for example) a large 3D array, I imagine using a loop would be quite inefficient.

Is there any method in Java to set all values in a certain array to true, or alternatively to set all values to true when the array is initialised?

(e.g

boolean[][][] newBool = new boolean[100][100][100];
newBool.setAllTrue();

//Rather than

for(int a = 0; a < 100; a++) {
    for(int b = 0; b < 100; b++) {
        for(int c = 0; c < 100; c++) {
            newBool[a][b][c] = true;
        }
    }
}

Upvotes: 13

Views: 31315

Answers (4)

Balvinder Kaur
Balvinder Kaur

Reputation: 1

boolean[] isPrime = new boolean[10];
 
Arrays.fill(isPrime, true);

This will assign all the elements of the array with true. Because by default the boolean array has all elements as false.

Upvotes: 0

Jack
Jack

Reputation: 370

You could use Java 7's Arrays.fill which assigns a specified value to every element of the specified array...so something like. This is still using a loop but at least is shorter to write.

boolean[] toFill = new boolean[100] {};
Arrays.fill(toFill, true);

Upvotes: 17

Kirill Solokhov
Kirill Solokhov

Reputation: 410

It's much better to use java.util.BitSet instead of array of booleans. In a BitSet you can set values in some range. It's memory effective because it uses array of longs for internal state.

BitSet bSet = new BitSet(10);
bSet.set(0,10);

Upvotes: 1

stinepike
stinepike

Reputation: 54672

There is no shortcut in this situation. and the best option is using a for loop. there might be several other options, like setting the value while declaring (!!). Or you can use Arrays.fill methods but internally it will use loop. or if possible then toggle the use of your values.

Upvotes: 2

Related Questions