Arrays.fill with multidimensional array in Java

Caroline picture Caroline · Aug 19, 2011 · Viewed 139.7k times · Source

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

Answer

aioobe picture aioobe · Aug 19, 2011

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