Java Arrays.fill()

alphachap picture alphachap · Mar 9, 2011 · Viewed 48.8k times · Source

How to fill a multidimensional array?

int[][] array = new int[4][6]; 
Arrays.fill(array, 0);

I tried it, but it doesn't work.

Answer

aioobe picture aioobe · Mar 9, 2011

Here's a suggestion using a for-each:

for (int[] row : array)
    Arrays.fill(row, 0);

You can verify that it works by doing

System.out.println(Arrays.deepToString(array));

A side note: Since you're creating the array, right before the fill, the fill is actually not needed (as long as you really want zeros in it). Java initializes all array-elements to their corresponding default values, and for int it is 0 :-)