将传递的二维布尔数组的所有值设置为 false?

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

我有一个名为 'test' 的二维布尔值,它包含 'true' 和 'false' 的内容,随机设置。

我正在尝试创建一个将 'test' 的所有内容设置为 false 的方法。

这是我的尝试:

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

如果您想知道为什么我在那里有 [1],答案是 "I don't know. At least eclipse would let me run it."

有谁知道正确的做法吗?

一如既往地感谢你,Whosebug。

试试这个。从逻辑上讲,这是正确的方法:

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

或者可以按照你想要的方式完成,像这样:

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

你几乎是正确的,只需遍历数组的第一级并在每个第二级数组上调用 Arrays.fill

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

请注意,二维数组基本上只是一个数组数组,即,如果您有 boolean[][],您将得到一个布尔数组数组。请注意,必须首先初始化第二级数组(即内部 boolean[]),即在创建二维数组之后所有内部数组都为空。

那是因为 Arrays.fill 采用单个数组。

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

} 

还有 streams 方法:

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