Reputation: 201
How to fill a multidimensional array?
int[][] array = new int[4][6];
Arrays.fill(array, 0);
I tried it, but it doesn't work.
Upvotes: 20
Views: 49844
Reputation: 321
See this way:
Arrays.fill(array[0], 0);
Arrays.fill(array, array[0]);
Upvotes: -3
Reputation: 74750
First, note that 0
is the default value for int arrays, so you don't have to fill something with 0.
If you want your array to stay truly multidimensional, you'll need a loop.
public static void fill(int[][] array, int element) {
for(int[] subarray : array) {
Arrays.fill(subarray, element);
}
}
If you only need a 2D-array filled with the same element and don't want to change the subarrays later, you can use this trick:
public static int[][] create2DArray(int length, int subLength, int element) {
int[] subArray = new int[subLength];
Arrays.fill(subArray, element);
int[][] array = new int[length][];
Arrays.fill(array, subArray);
return array;
}
This works analogously for higher-dimensional arrays.
Upvotes: 1
Reputation: 420951
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 :-)
Upvotes: 31
Reputation: 308753
Since array is really an array of arrays, perhaps you can try looping over each row and doing fill for each one individually.
Upvotes: 2
Reputation: 2155
Try this:
for(int i = 0; i < array.length; i++) {
Arrays.fill(array[i], 0);
}
I haven't tested it but I think it should work.
Upvotes: 13