Setting all values in a boolean array to true

23,930

Solution 1

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);

Solution 2

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.

Solution 3

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);
Share:
23,930
Fraser Price
Author by

Fraser Price

Updated on August 09, 2021

Comments

  • Fraser Price
    Fraser Price almost 3 years

    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;
            }
        }
    }
    
  • Amir Afghani
    Amir Afghani over 10 years
  • inquisitive
    inquisitive over 10 years
    -1 OP Specifically asked for 3D arrays. Arrays.fill work for 1D only.
  • Jack
    Jack over 10 years
    not so, you can do the same thing for a 3D array, I just assumed he could extrapolate himself boolean[][][] toFill = new boolean[100][100][100] {};
  • takendarkk
    takendarkk over 10 years
    If Arrays.fill uses a loop internally how is it any better efficiency wise than OP's example of using a loop?
  • Jack
    Jack over 10 years
    yes you're right, it's the same as a loop. just more concise. I don't think there's a way in Java to do it without a loop.