How to fill a multidimensional array?
int[][] array = new int[4][6];
Arrays.fill(array, 0);
I tried it, but it doesn't work.
fill() method is in java. util. Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array.
Solution. This example fill (initialize all the elements of the array in one short) an array by using Array. fill(arrayname,value) method and Array. fill(arrayname, starting index, ending index, value) method of Java Util class.
fill(double[] a, int fromIndex, int toIndex, double val) method assigns the specified double value to each element of the specified range of the specified array of doubles. The range to be filled extends from index fromIndex, inclusive, to index toIndex, exclusive.
Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With