m0a
m0a

Reputation: 1005

Set all values of a passed 2D boolean array to false?

I have a 2D boolean called 'test' that has contents of both 'true' and 'false', randomly set.

I'm trying to create a method that will set all contents of 'test' to false.

This is my attempt:

public static void clearArray( boolean[][] test) {
    Arrays.fill(test[1], false);
}   

If you're wondering why I have [1] there, the answer is "I don't know. At least eclipse would let me run it."

Does anyone know the correct way to do this?

Thank you as always, stackoverflow.

Upvotes: 1

Views: 2700

Answers (6)

OldCurmudgeon
OldCurmudgeon

Reputation: 65793

There's also the streams approach:

public static void clearArray(boolean[][] b) {
    Arrays.stream(b).forEach(a -> Arrays.fill(a, false));
}

public void test() {
    boolean[][] b = new boolean[4][4];
    for (int i = 0; i < b.length; i++) {
        b[i][i] = true;
    }
    System.out.println("Before:" + Arrays.deepToString(b));
    clearArray(b);
    System.out.println("After:" + Arrays.deepToString(b));
}

Upvotes: 2

Igor Devescovi
Igor Devescovi

Reputation: 31

public static void clearArray( boolean[][] test) {
    for(boolean[] inTest: test)
        Arrays.fill(inTest, false);

} 

Upvotes: 2

Thomas
Thomas

Reputation: 88707

You're almost correct, just loop over the first level of the array and call Arrays.fill on each 2nd level array.

public static void clearArray( boolean[][] test) {
  for( boolean[] secondLvl : test ) {
   Arrays.fill( secondLvl , false);
  }
}  

Note that 2D arrays are basically just an array of arrays, i.e. you get an array of boolean arrays if you have boolean[][]. Note that the second level array (i.e. the inner boolean[]) would have to be initialized first, i.e. right after creating the 2D array all inner arrays are null.

Upvotes: 3

burglarhobbit
burglarhobbit

Reputation: 2291

Try this. Logically, this is the correct way:

for(int i=0; i<test.length; i++) {
    for(int j=0; j<test[i].length; j++) {
        test[i][j] = false;
    }
}

Or it can be done the way you want, like this:

for(int i=0; i<test.length; i++) {
    Arrays.fill(test[i], false);
}

Upvotes: 2

Andriy Kuba
Andriy Kuba

Reputation: 8263

public static void clearArray( boolean[][] test) {
    for (boolean[] row: test) 
      Arrays.fill(row, false);
} 

Upvotes: 4

SacJn
SacJn

Reputation: 777

Thats because Arrays.fill takes single array.

public static void clearArray( boolean[][] test) 
{   
  for ( int i=0 ; i < test.rowCount; i++)
     Arrays.fill(test[i], false);     
}

Upvotes: 2

Related Questions