Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.fill with multidimensional array in Java

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

like image 630
Caroline Avatar asked Aug 19 '11 07:08

Caroline


People also ask

How do you fill a multi-dimensional array in Java?

We can use a loop to fill a multidimensional array. // given value. int [][]ar = new int [ 3 ][ 4 ]; // Fill each row with 10.

Can arrays be multidimensional in Java?

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.

Is a multidimensional array an array of 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.


2 Answers

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); 
like image 50
aioobe Avatar answered Sep 21 '22 22:09

aioobe


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); 
like image 42
trojanfoe Avatar answered Sep 20 '22 22:09

trojanfoe