How to fill a multidimensional array?
int[][] array = new int[4][6];
Arrays.fill(array, 0);
I tried it, but it doesn't work.
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 :-)
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.
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.
See this way:
Arrays.fill(array[0], 0);
Arrays.fill(array, array[0]);
array[0][0], you also change array[1][0], array[2][0], ... to the same value. Not a good solution.
int index = (y * width) + x;-- you could even create a class that just exposes get/set methods that take x and y as separate arguments. Then you could fill the whole array without any looping.