How can I fill a multidimensional array in Java without using a loop? I\'ve tried:
double[][] arr = new double[20][4];
Arrays.fill(arr, 0);
Arrays.fill(arr, new double[4]);
Arrays.fill works with single dimensional array, so to fill two dimensional array we can do below
for (int i = 0, len = arr.length; i < len; i++)
Arrays.fill(arr[i], 0);
As an extension to the answer, I found this post but was looking to fill a 4 dimensional array. The original example is only a two dimensional array, but the question says "multidimensional". I didn't want to post a new question for this...
You can use the same method, but you have to nest them so that you eventually get to a single dimensional array.
fourDArray = new float[10][10][10][1];
// Fill each row with null
for (float[][][] row: fourDArray)
{
for (float[][] innerRow: row)
{
for (float[] innerInnerRow: innerRow)
{
Arrays.fill(innerInnerRow, -1000);
}
}
};
The OP asked how to solve this problem without a loop! For some reason it is fashionable these days to avoid loops. Why is this? Probably there is a realization that using map
, reduce
, filter
, and friends, and methods like each
hide loops and cut down on program verbage and are kind of cool. The same goes for really sweet Unix pipelines. Or jQuery code. Things just look great without loops.
But does Java have a map
method? Not really, but we could define one with a Function
interface with an eval
or exec
method. It isn't too hard and would be a good exercise. It might be expensive and not used in practice.
Another way to do this without a loop is to use tail recursion. Yes, it is kind of silly and no one would use it in practice either, but it does show, maybe, that loops are fine in this case. Nevertheless, just to show "yet another loop free example" and to have fun, here is:
import java.util.Arrays;
public class FillExample {
private static void fillRowsWithZeros(double[][] a, int rows, int cols) {
if (rows >= 0) {
double[] row = new double[cols];
Arrays.fill(row, 0.0);
a[rows] = row;
fillRowsWithZeros(a, rows - 1, cols);
}
}
public static void main(String[] args) {
double[][] arr = new double[20][4];
fillRowsWithZeros(arr, arr.length - 1, arr[0].length);
System.out.println(Arrays.deepToString(arr));
}
}
It isn't pretty, but in answer to the OP's question, there are no explicit loops.
Arrays.fill works only with one-dimensional array
Source of java.util.Arrays:
public static void fill(Object[] a, Object val) {
int i = 0;
for(int len = a.length; i < len; ++i) {
a[i] = val;
}
Use own loops for initialization array
In simple words java donot provide such an API. You need to iterate through loop and using fill method you can fill 2D array with one loop.
int row = 5;
int col = 6;
int cache[][]=new int[row][col];
for(int i=0;i<=row;i++){
Arrays.fill(cache[i]);
}