Alex Rivera | Logout

Java Arrays.fill()

Asked 2011-03-09T21:53:47.060
20

How to fill a multidimensional array?

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

I tried it, but it doesn't work.

Edit
Report

1 Answer

31

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

answered 2011-03-09T21:59:02.153

Your Answer