How can I fill a multidimensional array in Java without using a loop? I've tried:
double[][] arr = new double[20][4];
Arrays.fill(arr, 0);
This results in java.lang.ArrayStoreException: java.lang.Double
Thanks in advance!
Another way to do this without a loop is to use tail recursion. Yes, it is kind of silly and no one would use it in practice either, but it does show, maybe, that loops are fine in this case. Nevertheless, just to show "yet another loop free example" and to have fun, here is:
import java.util.Arrays;
public class FillExample {
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[20][4];
fillRowsWithZeros(arr, arr.length - 1, arr[0].length);
System.out.println(Arrays.deepToString(arr));
}
}
It isn't pretty, but in answer to the OP's question, there are no explicit loops.
Arrays.fill with multidimensional array in Java
最新推荐文章于 2024-10-16 16:34:42 发布