Java Collection How to - Fill multidimensional array








Question

We would like to know how to fill multidimensional array.

Answer

import java.util.Arrays;
//from  w w  w .  j a  va2  s  .  co  m
public class Main {
  private static void fillRowsWithZeros(double[][] a, int rows, int cols) {
    if (rows >= 0) {
      double[] row = new double[cols];
      Arrays.fill(row, 0.0);
      a[rows] = row;
      fillRowsWithZeros(a, rows - 1, cols);
    }
  }

  public static void main(String[] args) {
    double[][] arr = new double[2][4];
    fillRowsWithZeros(arr, arr.length - 1, arr[0].length);
    System.out.println(Arrays.deepToString(arr));
  }
}

The code above generates the following result.