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
We can use a loop to fill a multidimensional array. // given value. int [][]ar = new int [ 3 ][ 4 ]; // Fill each row with 10.
No, Java does not support multi-dimensional arrays. Java supports arrays of arrays. In Java, a two-dimensional array is nothing but, an array of one-dimensional arrays.
A multidimensional array in MATLAB® is an array with more than two dimensions. In a matrix, the two dimensions are represented by rows and columns. Each element is defined by two subscripts, the row index and the column index.
This is because a double[][]
is an array of double[]
which you can't assign 0.0
to (it would be like doing double[] vector = 0.0
). In fact, Java has no true multidimensional arrays.
As it happens, 0.0
is the default value for doubles in Java, thus the matrix will actually already be filled with zeros when you get it from new
. However, if you wanted to fill it with, say, 1.0
you could do the following:
I don't believe the API provides a method to solve this without using a loop. It's simple enough however to do it with a for-each loop.
double[][] matrix = new double[20][4]; // Fill each row with 1.0 for (double[] row: matrix) Arrays.fill(row, 1.0);
double[][] arr = new double[20][4]; Arrays.fill(arr[0], 0); Arrays.fill(arr[1], 0); Arrays.fill(arr[2], 0); Arrays.fill(arr[3], 0); Arrays.fill(arr[4], 0); Arrays.fill(arr[5], 0); Arrays.fill(arr[6], 0); Arrays.fill(arr[7], 0); Arrays.fill(arr[8], 0); Arrays.fill(arr[9], 0); Arrays.fill(arr[10], 0); Arrays.fill(arr[11], 0); Arrays.fill(arr[12], 0); Arrays.fill(arr[13], 0); Arrays.fill(arr[14], 0); Arrays.fill(arr[15], 0); Arrays.fill(arr[16], 0); Arrays.fill(arr[17], 0); Arrays.fill(arr[18], 0); Arrays.fill(arr[19], 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With